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 = 338; //Uwe: support for polytonic Greek
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 // FIXME The caching mechanism could be improved. At present, we have a
208 // cache for each Buffer, that caches all the bibliography info for that
209 // Buffer. A more efficient solution would be to have a global cache per
210 // file, and then to construct the Buffer's bibinfo from that.
211 /// A cache for bibliography info
212 mutable BiblioInfo bibinfo_;
213 /// whether the bibinfo cache is valid
214 bool bibinfoCacheValid_;
215 /// Cache of timestamps of .bib files
216 map<FileName, time_t> bibfileStatus_;
218 mutable RefCache ref_cache_;
220 /// our Text that should be wrapped in an InsetText
225 /// Creates the per buffer temporary directory
226 static FileName createBufferTmpDir()
229 // We are in our own directory. Why bother to mangle name?
230 // In fact I wrote this code to circumvent a problematic behaviour
231 // (bug?) of EMX mkstemp().
232 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
233 convert<string>(count++));
235 if (!tmpfl.createDirectory(0777)) {
236 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
237 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
238 from_utf8(tmpfl.absFilename())));
244 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
245 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
246 read_only(readonly_), filename(file), file_fully_loaded(false),
247 toc_backend(&parent), macro_lock(false), timestamp_(0),
248 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false)
250 temppath = createBufferTmpDir();
251 lyxvc.setBuffer(&parent);
253 wa_ = new frontend::WorkAreaManager;
257 Buffer::Buffer(string const & file, bool readonly)
258 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
260 LYXERR(Debug::INFO, "Buffer::Buffer()");
262 d->inset.setBuffer(*this);
263 d->inset.initParagraphs(*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
278 // clear references to children in macro tables
279 d->children_positions.clear();
280 d->position_to_children.clear();
282 if (!d->temppath.destroyDirectory()) {
283 Alert::warning(_("Could not remove temporary directory"),
284 bformat(_("Could not remove the temporary directory %1$s"),
285 from_utf8(d->temppath.absFilename())));
288 // Remove any previewed LaTeX snippets associated with this buffer.
289 graphics::Previews::get().removeLoader(*this);
295 void Buffer::changed() const
302 frontend::WorkAreaManager & Buffer::workAreaManager() const
304 LASSERT(d->wa_, /**/);
309 Text & Buffer::text() const
311 return const_cast<Text &>(d->inset.text_);
315 Inset & Buffer::inset() const
317 return const_cast<InsetText &>(d->inset);
321 BufferParams & Buffer::params()
327 BufferParams const & Buffer::params() const
333 ParagraphList & Buffer::paragraphs()
335 return text().paragraphs();
339 ParagraphList const & Buffer::paragraphs() const
341 return text().paragraphs();
345 LyXVC & Buffer::lyxvc()
351 LyXVC const & Buffer::lyxvc() const
357 string const Buffer::temppath() const
359 return d->temppath.absFilename();
363 TexRow const & Buffer::texrow() const
369 TocBackend & Buffer::tocBackend() const
371 return d->toc_backend;
375 Undo & Buffer::undo()
381 string Buffer::latexName(bool const no_path) const
383 FileName latex_name = makeLatexName(d->filename);
384 return no_path ? latex_name.onlyFileName()
385 : latex_name.absFilename();
389 string Buffer::logName(LogType * type) const
391 string const filename = latexName(false);
393 if (filename.empty()) {
399 string const path = temppath();
401 FileName const fname(addName(temppath(),
402 onlyFilename(changeExtension(filename,
404 FileName const bname(
405 addName(path, onlyFilename(
406 changeExtension(filename,
407 formats.extension("literate") + ".out"))));
409 // If no Latex log or Build log is newer, show Build log
411 if (bname.exists() &&
412 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
413 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
416 return bname.absFilename();
418 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
421 return fname.absFilename();
425 void Buffer::setReadonly(bool const flag)
427 if (d->read_only != flag) {
434 void Buffer::setFileName(string const & newfile)
436 d->filename = makeAbsPath(newfile);
437 setReadonly(d->filename.isReadOnly());
442 int Buffer::readHeader(Lexer & lex)
444 int unknown_tokens = 0;
446 int begin_header_line = -1;
448 // Initialize parameters that may be/go lacking in header:
449 params().branchlist().clear();
450 params().preamble.erase();
451 params().options.erase();
452 params().master.erase();
453 params().float_placement.erase();
454 params().paperwidth.erase();
455 params().paperheight.erase();
456 params().leftmargin.erase();
457 params().rightmargin.erase();
458 params().topmargin.erase();
459 params().bottommargin.erase();
460 params().headheight.erase();
461 params().headsep.erase();
462 params().footskip.erase();
463 params().columnsep.erase();
464 params().fontsCJK.erase();
465 params().listings_params.clear();
466 params().clearLayoutModules();
467 params().pdfoptions().clear();
469 for (int i = 0; i < 4; ++i) {
470 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
471 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
474 ErrorList & errorList = d->errorLists["Parse"];
483 if (token == "\\end_header")
487 if (token == "\\begin_header") {
488 begin_header_line = line;
492 LYXERR(Debug::PARSER, "Handling document header token: `"
495 string unknown = params().readToken(lex, token, d->filename.onlyPath());
496 if (!unknown.empty()) {
497 if (unknown[0] != '\\' && token == "\\textclass") {
498 Alert::warning(_("Unknown document class"),
499 bformat(_("Using the default document class, because the "
500 "class %1$s is unknown."), from_utf8(unknown)));
503 docstring const s = bformat(_("Unknown token: "
507 errorList.push_back(ErrorItem(_("Document header error"),
512 if (begin_header_line) {
513 docstring const s = _("\\begin_header is missing");
514 errorList.push_back(ErrorItem(_("Document header error"),
518 params().makeDocumentClass();
520 return unknown_tokens;
525 // changed to be public and have one parameter
526 // Returns false if "\end_document" is not read (Asger)
527 bool Buffer::readDocument(Lexer & lex)
529 ErrorList & errorList = d->errorLists["Parse"];
532 if (!lex.checkFor("\\begin_document")) {
533 docstring const s = _("\\begin_document is missing");
534 errorList.push_back(ErrorItem(_("Document header error"),
538 // we are reading in a brand new document
539 LASSERT(paragraphs().empty(), /**/);
543 if (params().outputChanges) {
544 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
545 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
546 LaTeXFeatures::isAvailable("xcolor");
548 if (!dvipost && !xcolorsoul) {
549 Alert::warning(_("Changes not shown in LaTeX output"),
550 _("Changes will not be highlighted in LaTeX output, "
551 "because neither dvipost nor xcolor/soul are installed.\n"
552 "Please install these packages or redefine "
553 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
554 } else if (!xcolorsoul) {
555 Alert::warning(_("Changes not shown in LaTeX output"),
556 _("Changes will not be highlighted in LaTeX output "
557 "when using pdflatex, because xcolor and soul are not installed.\n"
558 "Please install both packages or redefine "
559 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
563 if (!params().master.empty()) {
564 FileName const master_file = makeAbsPath(params().master,
565 onlyPath(absFileName()));
566 if (isLyXFilename(master_file.absFilename())) {
567 Buffer * master = checkAndLoadLyXFile(master_file);
568 d->parent_buffer = master;
573 bool const res = text().read(*this, lex, errorList, &(d->inset));
576 updateMacroInstances();
581 // needed to insert the selection
582 void Buffer::insertStringAsLines(ParagraphList & pars,
583 pit_type & pit, pos_type & pos,
584 Font const & fn, docstring const & str, bool autobreakrows)
588 // insert the string, don't insert doublespace
589 bool space_inserted = true;
590 for (docstring::const_iterator cit = str.begin();
591 cit != str.end(); ++cit) {
592 Paragraph & par = pars[pit];
594 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
595 breakParagraph(params(), pars, pit, pos,
596 par.layout().isEnvironment());
599 space_inserted = true;
603 // do not insert consecutive spaces if !free_spacing
604 } else if ((*cit == ' ' || *cit == '\t') &&
605 space_inserted && !par.isFreeSpacing()) {
607 } else if (*cit == '\t') {
608 if (!par.isFreeSpacing()) {
609 // tabs are like spaces here
610 par.insertChar(pos, ' ', font, params().trackChanges);
612 space_inserted = true;
614 const pos_type n = 8 - pos % 8;
615 for (pos_type i = 0; i < n; ++i) {
616 par.insertChar(pos, ' ', font, params().trackChanges);
619 space_inserted = true;
621 } else if (!isPrintable(*cit)) {
622 // Ignore unprintables
625 // just insert the character
626 par.insertChar(pos, *cit, font, params().trackChanges);
628 space_inserted = (*cit == ' ');
635 bool Buffer::readString(string const & s)
637 params().compressed = false;
639 // remove dummy empty par
640 paragraphs().clear();
644 FileName const name = FileName::tempName();
645 switch (readFile(lex, name, true)) {
649 // We need to call lyx2lyx, so write the input to a file
650 ofstream os(name.toFilesystemEncoding().c_str());
653 return readFile(name);
663 bool Buffer::readFile(FileName const & filename)
665 FileName fname(filename);
667 // remove dummy empty par
668 paragraphs().clear();
671 if (readFile(lex, fname) != success)
678 bool Buffer::isFullyLoaded() const
680 return d->file_fully_loaded;
684 void Buffer::setFullyLoaded(bool value)
686 d->file_fully_loaded = value;
690 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
693 LASSERT(!filename.empty(), /**/);
695 // the first (non-comment) token _must_ be...
696 if (!lex.checkFor("\\lyxformat")) {
697 Alert::error(_("Document format failure"),
698 bformat(_("%1$s is not a readable LyX document."),
699 from_utf8(filename.absFilename())));
705 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
706 // if present remove ".," from string.
707 size_t dot = tmp_format.find_first_of(".,");
708 //lyxerr << " dot found at " << dot << endl;
709 if (dot != string::npos)
710 tmp_format.erase(dot, 1);
711 int const file_format = convert<int>(tmp_format);
712 //lyxerr << "format: " << file_format << endl;
714 // save timestamp and checksum of the original disk file, making sure
715 // to not overwrite them with those of the file created in the tempdir
716 // when it has to be converted to the current format.
718 // Save the timestamp and checksum of disk file. If filename is an
719 // emergency file, save the timestamp and checksum of the original lyx file
720 // because isExternallyModified will check for this file. (BUG4193)
721 string diskfile = filename.absFilename();
722 if (suffixIs(diskfile, ".emergency"))
723 diskfile = diskfile.substr(0, diskfile.size() - 10);
724 saveCheckSum(FileName(diskfile));
727 if (file_format != LYX_FORMAT) {
730 // lyx2lyx would fail
733 FileName const tmpfile = FileName::tempName();
734 if (tmpfile.empty()) {
735 Alert::error(_("Conversion failed"),
736 bformat(_("%1$s is from a different"
737 " version of LyX, but a temporary"
738 " file for converting it could"
740 from_utf8(filename.absFilename())));
743 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
744 if (lyx2lyx.empty()) {
745 Alert::error(_("Conversion script not found"),
746 bformat(_("%1$s is from a different"
747 " version of LyX, but the"
748 " conversion script lyx2lyx"
749 " could not be found."),
750 from_utf8(filename.absFilename())));
753 ostringstream command;
754 command << os::python()
755 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
756 << " -t " << convert<string>(LYX_FORMAT)
757 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
758 << ' ' << quoteName(filename.toFilesystemEncoding());
759 string const command_str = command.str();
761 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
763 cmd_ret const ret = runCommand(command_str);
764 if (ret.first != 0) {
765 Alert::error(_("Conversion script failed"),
766 bformat(_("%1$s is from a different version"
767 " of LyX, but the lyx2lyx script"
768 " failed to convert it."),
769 from_utf8(filename.absFilename())));
772 bool const ret = readFile(tmpfile);
773 // Do stuff with tmpfile name and buffer name here.
774 return ret ? success : failure;
779 if (readDocument(lex)) {
780 Alert::error(_("Document format failure"),
781 bformat(_("%1$s ended unexpectedly, which means"
782 " that it is probably corrupted."),
783 from_utf8(filename.absFilename())));
786 d->file_fully_loaded = true;
791 // Should probably be moved to somewhere else: BufferView? LyXView?
792 bool Buffer::save() const
794 // We don't need autosaves in the immediate future. (Asger)
795 resetAutosaveTimers();
797 string const encodedFilename = d->filename.toFilesystemEncoding();
800 bool madeBackup = false;
802 // make a backup if the file already exists
803 if (lyxrc.make_backup && fileName().exists()) {
804 backupName = FileName(absFileName() + '~');
805 if (!lyxrc.backupdir_path.empty()) {
806 string const mangledName =
807 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
808 backupName = FileName(addName(lyxrc.backupdir_path,
811 if (fileName().copyTo(backupName)) {
814 Alert::error(_("Backup failure"),
815 bformat(_("Cannot create backup file %1$s.\n"
816 "Please check whether the directory exists and is writeable."),
817 from_utf8(backupName.absFilename())));
818 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
822 // ask if the disk file has been externally modified (use checksum method)
823 if (fileName().exists() && isExternallyModified(checksum_method)) {
824 docstring const file = makeDisplayPath(absFileName(), 20);
825 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
826 "you want to overwrite this file?"), file);
827 int const ret = Alert::prompt(_("Overwrite modified file?"),
828 text, 1, 1, _("&Overwrite"), _("&Cancel"));
833 if (writeFile(d->filename)) {
837 // Saving failed, so backup is not backup
839 backupName.moveTo(d->filename);
845 bool Buffer::writeFile(FileName const & fname) const
847 if (d->read_only && fname == d->filename)
852 docstring const str = bformat(_("Saving document %1$s..."),
853 makeDisplayPath(fname.absFilename()));
856 if (params().compressed) {
857 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
858 retval = ofs && write(ofs);
860 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
861 retval = ofs && write(ofs);
865 message(str + _(" could not write file!"));
869 removeAutosaveFile(d->filename.absFilename());
871 saveCheckSum(d->filename);
872 message(str + _(" done."));
878 bool Buffer::write(ostream & ofs) const
881 // Use the standard "C" locale for file output.
882 ofs.imbue(locale::classic());
885 // The top of the file should not be written by params().
887 // write out a comment in the top of the file
888 ofs << "#LyX " << lyx_version
889 << " created this file. For more info see http://www.lyx.org/\n"
890 << "\\lyxformat " << LYX_FORMAT << "\n"
891 << "\\begin_document\n";
893 /// For each author, set 'used' to true if there is a change
894 /// by this author in the document; otherwise set it to 'false'.
895 AuthorList::Authors::const_iterator a_it = params().authors().begin();
896 AuthorList::Authors::const_iterator a_end = params().authors().end();
897 for (; a_it != a_end; ++a_it)
898 a_it->second.setUsed(false);
900 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
901 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
902 for ( ; it != end; ++it)
903 it->checkAuthors(params().authors());
905 // now write out the buffer parameters.
906 ofs << "\\begin_header\n";
907 params().writeFile(ofs);
908 ofs << "\\end_header\n";
911 ofs << "\n\\begin_body\n";
912 text().write(*this, ofs);
913 ofs << "\n\\end_body\n";
915 // Write marker that shows file is complete
916 ofs << "\\end_document" << endl;
918 // Shouldn't really be needed....
921 // how to check if close went ok?
922 // Following is an attempt... (BE 20001011)
924 // good() returns false if any error occured, including some
926 // bad() returns true if something bad happened in the buffer,
927 // which should include file system full errors.
932 lyxerr << "File was not closed properly." << endl;
939 bool Buffer::makeLaTeXFile(FileName const & fname,
940 string const & original_path,
941 OutputParams const & runparams,
942 bool output_preamble, bool output_body) const
944 string const encoding = runparams.encoding->iconvName();
945 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
948 try { ofs.reset(encoding); }
949 catch (iconv_codecvt_facet_exception & e) {
950 lyxerr << "Caught iconv exception: " << e.what() << endl;
951 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
952 "verify that the support software for your encoding (%1$s) is "
953 "properly installed"), from_ascii(encoding)));
956 if (!openFileWrite(ofs, fname))
959 //TexStream ts(ofs.rdbuf(), &texrow());
960 ErrorList & errorList = d->errorLists["Export"];
962 bool failed_export = false;
965 writeLaTeXSource(ofs, original_path,
966 runparams, output_preamble, output_body);
968 catch (EncodingException & e) {
969 odocstringstream ods;
970 ods.put(e.failed_char);
972 oss << "0x" << hex << e.failed_char << dec;
973 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
974 " (code point %2$s)"),
975 ods.str(), from_utf8(oss.str()));
976 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
977 "representable in the chosen encoding.\n"
978 "Changing the document encoding to utf8 could help."),
979 e.par_id, e.pos, e.pos + 1));
980 failed_export = true;
982 catch (iconv_codecvt_facet_exception & e) {
983 errorList.push_back(ErrorItem(_("iconv conversion failed"),
984 _(e.what()), -1, 0, 0));
985 failed_export = true;
987 catch (exception const & e) {
988 errorList.push_back(ErrorItem(_("conversion failed"),
989 _(e.what()), -1, 0, 0));
990 failed_export = true;
993 lyxerr << "Caught some really weird exception..." << endl;
999 failed_export = true;
1000 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1004 return !failed_export;
1008 void Buffer::writeLaTeXSource(odocstream & os,
1009 string const & original_path,
1010 OutputParams const & runparams_in,
1011 bool const output_preamble, bool const output_body) const
1013 // The child documents, if any, shall be already loaded at this point.
1015 OutputParams runparams = runparams_in;
1017 // validate the buffer.
1018 LYXERR(Debug::LATEX, " Validating buffer...");
1019 LaTeXFeatures features(*this, params(), runparams);
1021 LYXERR(Debug::LATEX, " Buffer validation done.");
1023 // The starting paragraph of the coming rows is the
1024 // first paragraph of the document. (Asger)
1025 if (output_preamble && runparams.nice) {
1026 os << "%% LyX " << lyx_version << " created this file. "
1027 "For more info, see http://www.lyx.org/.\n"
1028 "%% Do not edit unless you really know what "
1030 d->texrow.newline();
1031 d->texrow.newline();
1033 LYXERR(Debug::INFO, "lyx document header finished");
1035 // Don't move this behind the parent_buffer=0 code below,
1036 // because then the macros will not get the right "redefinition"
1037 // flag as they don't see the parent macros which are output before.
1040 // fold macros if possible, still with parent buffer as the
1041 // macros will be put in the prefix anyway.
1042 updateMacroInstances();
1044 // There are a few differences between nice LaTeX and usual files:
1045 // usual is \batchmode and has a
1046 // special input@path to allow the including of figures
1047 // with either \input or \includegraphics (what figinsets do).
1048 // input@path is set when the actual parameter
1049 // original_path is set. This is done for usual tex-file, but not
1050 // for nice-latex-file. (Matthias 250696)
1051 // Note that input@path is only needed for something the user does
1052 // in the preamble, included .tex files or ERT, files included by
1053 // LyX work without it.
1054 if (output_preamble) {
1055 if (!runparams.nice) {
1056 // code for usual, NOT nice-latex-file
1057 os << "\\batchmode\n"; // changed
1058 // from \nonstopmode
1059 d->texrow.newline();
1061 if (!original_path.empty()) {
1063 // We don't know the encoding of inputpath
1064 docstring const inputpath = from_utf8(latex_path(original_path));
1065 os << "\\makeatletter\n"
1066 << "\\def\\input@path{{"
1067 << inputpath << "/}}\n"
1068 << "\\makeatother\n";
1069 d->texrow.newline();
1070 d->texrow.newline();
1071 d->texrow.newline();
1074 // get parent macros (if this buffer has a parent) which will be
1075 // written at the document begin further down.
1076 MacroSet parentMacros;
1077 listParentMacros(parentMacros, features);
1079 // Write the preamble
1080 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1086 os << "\\begin{document}\n";
1087 d->texrow.newline();
1089 // output the parent macros
1090 MacroSet::iterator it = parentMacros.begin();
1091 MacroSet::iterator end = parentMacros.end();
1092 for (; it != end; ++it)
1093 (*it)->write(os, true);
1094 } // output_preamble
1096 d->texrow.start(paragraphs().begin()->id(), 0);
1098 LYXERR(Debug::INFO, "preamble finished, now the body.");
1100 // if we are doing a real file with body, even if this is the
1101 // child of some other buffer, let's cut the link here.
1102 // This happens for example if only a child document is printed.
1103 Buffer const * save_parent = 0;
1104 if (output_preamble) {
1105 save_parent = d->parent_buffer;
1106 d->parent_buffer = 0;
1110 latexParagraphs(*this, text(), os, d->texrow, runparams);
1112 // Restore the parenthood if needed
1113 if (output_preamble)
1114 d->parent_buffer = save_parent;
1116 // add this just in case after all the paragraphs
1118 d->texrow.newline();
1120 if (output_preamble) {
1121 os << "\\end{document}\n";
1122 d->texrow.newline();
1123 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1125 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1127 runparams_in.encoding = runparams.encoding;
1129 // Just to be sure. (Asger)
1130 d->texrow.newline();
1132 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1133 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1137 bool Buffer::isLatex() const
1139 return params().documentClass().outputType() == LATEX;
1143 bool Buffer::isLiterate() const
1145 return params().documentClass().outputType() == LITERATE;
1149 bool Buffer::isDocBook() const
1151 return params().documentClass().outputType() == DOCBOOK;
1155 void Buffer::makeDocBookFile(FileName const & fname,
1156 OutputParams const & runparams,
1157 bool const body_only) const
1159 LYXERR(Debug::LATEX, "makeDocBookFile...");
1162 if (!openFileWrite(ofs, fname))
1165 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1169 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1173 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1174 OutputParams const & runparams,
1175 bool const only_body) const
1177 LaTeXFeatures features(*this, params(), runparams);
1182 DocumentClass const & tclass = params().documentClass();
1183 string const top_element = tclass.latexname();
1186 if (runparams.flavor == OutputParams::XML)
1187 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1190 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1193 if (! tclass.class_header().empty())
1194 os << from_ascii(tclass.class_header());
1195 else if (runparams.flavor == OutputParams::XML)
1196 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1197 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1199 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1201 docstring preamble = from_utf8(params().preamble);
1202 if (runparams.flavor != OutputParams::XML ) {
1203 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1204 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1205 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1206 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1209 string const name = runparams.nice
1210 ? changeExtension(absFileName(), ".sgml") : fname;
1211 preamble += features.getIncludedFiles(name);
1212 preamble += features.getLyXSGMLEntities();
1214 if (!preamble.empty()) {
1215 os << "\n [ " << preamble << " ]";
1220 string top = top_element;
1222 if (runparams.flavor == OutputParams::XML)
1223 top += params().language->code();
1225 top += params().language->code().substr(0,2);
1228 if (!params().options.empty()) {
1230 top += params().options;
1233 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1234 << " file was created by LyX " << lyx_version
1235 << "\n See http://www.lyx.org/ for more information -->\n";
1237 params().documentClass().counters().reset();
1241 sgml::openTag(os, top);
1243 docbookParagraphs(paragraphs(), *this, os, runparams);
1244 sgml::closeTag(os, top_element);
1248 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1249 // Other flags: -wall -v0 -x
1250 int Buffer::runChktex()
1254 // get LaTeX-Filename
1255 FileName const path(temppath());
1256 string const name = addName(path.absFilename(), latexName());
1257 string const org_path = filePath();
1259 PathChanger p(path); // path to LaTeX file
1260 message(_("Running chktex..."));
1262 // Generate the LaTeX file if neccessary
1263 OutputParams runparams(¶ms().encoding());
1264 runparams.flavor = OutputParams::LATEX;
1265 runparams.nice = false;
1266 makeLaTeXFile(FileName(name), org_path, runparams);
1269 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1270 int const res = chktex.run(terr); // run chktex
1273 Alert::error(_("chktex failure"),
1274 _("Could not run chktex successfully."));
1275 } else if (res > 0) {
1276 ErrorList & errlist = d->errorLists["ChkTeX"];
1278 bufferErrors(terr, errlist);
1289 void Buffer::validate(LaTeXFeatures & features) const
1291 params().validate(features);
1295 for_each(paragraphs().begin(), paragraphs().end(),
1296 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1298 if (lyxerr.debugging(Debug::LATEX)) {
1299 features.showStruct();
1304 void Buffer::getLabelList(vector<docstring> & list) const
1306 // If this is a child document, use the parent's list instead.
1307 if (d->parent_buffer) {
1308 d->parent_buffer->getLabelList(list);
1313 Toc & toc = d->toc_backend.toc("label");
1314 TocIterator toc_it = toc.begin();
1315 TocIterator end = toc.end();
1316 for (; toc_it != end; ++toc_it) {
1317 if (toc_it->depth() == 0)
1318 list.push_back(toc_it->str());
1323 void Buffer::updateBibfilesCache() const
1325 // If this is a child document, use the parent's cache instead.
1326 if (d->parent_buffer) {
1327 d->parent_buffer->updateBibfilesCache();
1331 d->bibfilesCache_.clear();
1332 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1333 if (it->lyxCode() == BIBTEX_CODE) {
1334 InsetBibtex const & inset =
1335 static_cast<InsetBibtex const &>(*it);
1336 support::FileNameList const bibfiles = inset.getBibFiles();
1337 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1340 } else if (it->lyxCode() == INCLUDE_CODE) {
1341 InsetInclude & inset =
1342 static_cast<InsetInclude &>(*it);
1343 inset.updateBibfilesCache();
1344 support::FileNameList const & bibfiles =
1345 inset.getBibfilesCache(*this);
1346 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1351 // the bibinfo cache is now invalid
1352 d->bibinfoCacheValid_ = false;
1356 void Buffer::invalidateBibinfoCache()
1358 d->bibinfoCacheValid_ = false;
1362 support::FileNameList const & Buffer::getBibfilesCache() const
1364 // If this is a child document, use the parent's cache instead.
1365 if (d->parent_buffer)
1366 return d->parent_buffer->getBibfilesCache();
1368 // We update the cache when first used instead of at loading time.
1369 if (d->bibfilesCache_.empty())
1370 const_cast<Buffer *>(this)->updateBibfilesCache();
1372 return d->bibfilesCache_;
1376 BiblioInfo const & Buffer::masterBibInfo() const
1378 // if this is a child document and the parent is already loaded
1379 // use the parent's list instead [ale990412]
1380 Buffer const * const tmp = masterBuffer();
1383 return tmp->masterBibInfo();
1384 return localBibInfo();
1388 BiblioInfo const & Buffer::localBibInfo() const
1390 if (d->bibinfoCacheValid_) {
1391 support::FileNameList const & bibfilesCache = getBibfilesCache();
1392 // compare the cached timestamps with the actual ones.
1393 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1394 support::FileNameList::const_iterator en = bibfilesCache.end();
1395 for (; ei != en; ++ ei) {
1396 time_t lastw = ei->lastModified();
1397 if (lastw != d->bibfileStatus_[*ei]) {
1398 d->bibinfoCacheValid_ = false;
1399 d->bibfileStatus_[*ei] = lastw;
1405 if (!d->bibinfoCacheValid_) {
1406 d->bibinfo_.clear();
1407 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1408 it->fillWithBibKeys(d->bibinfo_, it);
1409 d->bibinfoCacheValid_ = true;
1415 bool Buffer::isDepClean(string const & name) const
1417 DepClean::const_iterator const it = d->dep_clean.find(name);
1418 if (it == d->dep_clean.end())
1424 void Buffer::markDepClean(string const & name)
1426 d->dep_clean[name] = true;
1430 bool Buffer::dispatch(string const & command, bool * result)
1432 return dispatch(lyxaction.lookupFunc(command), result);
1436 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1438 bool dispatched = true;
1440 switch (func.action) {
1441 case LFUN_BUFFER_EXPORT: {
1442 bool const tmp = doExport(to_utf8(func.argument()), false);
1448 case LFUN_BRANCH_ACTIVATE:
1449 case LFUN_BRANCH_DEACTIVATE: {
1450 BranchList & branchList = params().branchlist();
1451 docstring const branchName = func.argument();
1452 Branch * branch = branchList.find(branchName);
1454 LYXERR0("Branch " << branchName << " does not exist.");
1456 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1468 void Buffer::changeLanguage(Language const * from, Language const * to)
1470 LASSERT(from, /**/);
1473 for_each(par_iterator_begin(),
1475 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1479 bool Buffer::isMultiLingual() const
1481 ParConstIterator end = par_iterator_end();
1482 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1483 if (it->isMultiLingual(params()))
1490 DocIterator Buffer::getParFromID(int const id) const
1493 // John says this is called with id == -1 from undo
1494 lyxerr << "getParFromID(), id: " << id << endl;
1495 return doc_iterator_end(inset());
1498 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1499 if (it.paragraph().id() == id)
1502 return doc_iterator_end(inset());
1506 bool Buffer::hasParWithID(int const id) const
1508 return !getParFromID(id).atEnd();
1512 ParIterator Buffer::par_iterator_begin()
1514 return ParIterator(doc_iterator_begin(inset()));
1518 ParIterator Buffer::par_iterator_end()
1520 return ParIterator(doc_iterator_end(inset()));
1524 ParConstIterator Buffer::par_iterator_begin() const
1526 return lyx::par_const_iterator_begin(inset());
1530 ParConstIterator Buffer::par_iterator_end() const
1532 return lyx::par_const_iterator_end(inset());
1536 Language const * Buffer::language() const
1538 return params().language;
1542 docstring const Buffer::B_(string const & l10n) const
1544 return params().B_(l10n);
1548 bool Buffer::isClean() const
1550 return d->lyx_clean;
1554 bool Buffer::isBakClean() const
1556 return d->bak_clean;
1560 bool Buffer::isExternallyModified(CheckMethod method) const
1562 LASSERT(d->filename.exists(), /**/);
1563 // if method == timestamp, check timestamp before checksum
1564 return (method == checksum_method
1565 || d->timestamp_ != d->filename.lastModified())
1566 && d->checksum_ != d->filename.checksum();
1570 void Buffer::saveCheckSum(FileName const & file) const
1572 if (file.exists()) {
1573 d->timestamp_ = file.lastModified();
1574 d->checksum_ = file.checksum();
1576 // in the case of save to a new file.
1583 void Buffer::markClean() const
1585 if (!d->lyx_clean) {
1586 d->lyx_clean = true;
1589 // if the .lyx file has been saved, we don't need an
1591 d->bak_clean = true;
1595 void Buffer::markBakClean() const
1597 d->bak_clean = true;
1601 void Buffer::setUnnamed(bool flag)
1607 bool Buffer::isUnnamed() const
1613 // FIXME: this function should be moved to buffer_pimpl.C
1614 void Buffer::markDirty()
1617 d->lyx_clean = false;
1620 d->bak_clean = false;
1622 DepClean::iterator it = d->dep_clean.begin();
1623 DepClean::const_iterator const end = d->dep_clean.end();
1625 for (; it != end; ++it)
1630 FileName Buffer::fileName() const
1636 string Buffer::absFileName() const
1638 return d->filename.absFilename();
1642 string Buffer::filePath() const
1644 return d->filename.onlyPath().absFilename() + "/";
1648 bool Buffer::isReadonly() const
1650 return d->read_only;
1654 void Buffer::setParent(Buffer const * buffer)
1656 // Avoids recursive include.
1657 d->parent_buffer = buffer == this ? 0 : buffer;
1662 Buffer const * Buffer::parent()
1664 return d->parent_buffer;
1668 Buffer const * Buffer::masterBuffer() const
1670 if (!d->parent_buffer)
1673 return d->parent_buffer->masterBuffer();
1677 template<typename M>
1678 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1683 typename M::iterator it = m.lower_bound(x);
1684 if (it == m.begin())
1692 MacroData const * Buffer::getBufferMacro(docstring const & name,
1693 DocIterator const & pos) const
1695 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1697 // if paragraphs have no macro context set, pos will be empty
1701 // we haven't found anything yet
1702 DocIterator bestPos = par_iterator_begin();
1703 MacroData const * bestData = 0;
1705 // find macro definitions for name
1706 Impl::NamePositionScopeMacroMap::iterator nameIt
1707 = d->macros.find(name);
1708 if (nameIt != d->macros.end()) {
1709 // find last definition in front of pos or at pos itself
1710 Impl::PositionScopeMacroMap::const_iterator it
1711 = greatest_below(nameIt->second, pos);
1712 if (it != nameIt->second.end()) {
1714 // scope ends behind pos?
1715 if (pos < it->second.first) {
1716 // Looks good, remember this. If there
1717 // is no external macro behind this,
1718 // we found the right one already.
1719 bestPos = it->first;
1720 bestData = &it->second.second;
1724 // try previous macro if there is one
1725 if (it == nameIt->second.begin())
1732 // find macros in included files
1733 Impl::PositionScopeBufferMap::const_iterator it
1734 = greatest_below(d->position_to_children, pos);
1735 if (it == d->position_to_children.end())
1736 // no children before
1740 // do we know something better (i.e. later) already?
1741 if (it->first < bestPos )
1744 // scope ends behind pos?
1745 if (pos < it->second.first) {
1746 // look for macro in external file
1747 d->macro_lock = true;
1748 MacroData const * data
1749 = it->second.second->getMacro(name, false);
1750 d->macro_lock = false;
1752 bestPos = it->first;
1758 // try previous file if there is one
1759 if (it == d->position_to_children.begin())
1764 // return the best macro we have found
1769 MacroData const * Buffer::getMacro(docstring const & name,
1770 DocIterator const & pos, bool global) const
1775 // query buffer macros
1776 MacroData const * data = getBufferMacro(name, pos);
1780 // If there is a master buffer, query that
1781 if (d->parent_buffer) {
1782 d->macro_lock = true;
1783 MacroData const * macro = d->parent_buffer->getMacro(
1784 name, *this, false);
1785 d->macro_lock = false;
1791 data = MacroTable::globalMacros().get(name);
1800 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1802 // set scope end behind the last paragraph
1803 DocIterator scope = par_iterator_begin();
1804 scope.pit() = scope.lastpit() + 1;
1806 return getMacro(name, scope, global);
1810 MacroData const * Buffer::getMacro(docstring const & name,
1811 Buffer const & child, bool global) const
1813 // look where the child buffer is included first
1814 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1815 if (it == d->children_positions.end())
1818 // check for macros at the inclusion position
1819 return getMacro(name, it->second, global);
1823 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1825 pit_type lastpit = it.lastpit();
1827 // look for macros in each paragraph
1828 while (it.pit() <= lastpit) {
1829 Paragraph & par = it.paragraph();
1831 // iterate over the insets of the current paragraph
1832 InsetList const & insets = par.insetList();
1833 InsetList::const_iterator iit = insets.begin();
1834 InsetList::const_iterator end = insets.end();
1835 for (; iit != end; ++iit) {
1836 it.pos() = iit->pos;
1838 // is it a nested text inset?
1839 if (iit->inset->asInsetText()) {
1840 // Inset needs its own scope?
1841 InsetText const * itext
1842 = iit->inset->asInsetText();
1843 bool newScope = itext->isMacroScope();
1845 // scope which ends just behind the inset
1846 DocIterator insetScope = it;
1849 // collect macros in inset
1850 it.push_back(CursorSlice(*iit->inset));
1851 updateMacros(it, newScope ? insetScope : scope);
1856 // is it an external file?
1857 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1858 // get buffer of external file
1859 InsetCommand const & inset
1860 = static_cast<InsetCommand const &>(*iit->inset);
1861 InsetCommandParams const & ip = inset.params();
1862 d->macro_lock = true;
1863 Buffer * child = loadIfNeeded(*this, ip);
1864 d->macro_lock = false;
1868 // register its position, but only when it is
1869 // included first in the buffer
1870 if (d->children_positions.find(child)
1871 == d->children_positions.end())
1872 d->children_positions[child] = it;
1874 // register child with its scope
1875 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1879 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1883 MathMacroTemplate & macroTemplate
1884 = static_cast<MathMacroTemplate &>(*iit->inset);
1885 MacroContext mc(*this, it);
1886 macroTemplate.updateToContext(mc);
1889 bool valid = macroTemplate.validMacro();
1890 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1891 // then the BufferView's cursor will be invalid in
1892 // some cases which leads to crashes.
1897 d->macros[macroTemplate.name()][it] =
1898 Impl::ScopeMacro(scope, MacroData(*this, it));
1908 void Buffer::updateMacros() const
1913 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1915 // start with empty table
1917 d->children_positions.clear();
1918 d->position_to_children.clear();
1920 // Iterate over buffer, starting with first paragraph
1921 // The scope must be bigger than any lookup DocIterator
1922 // later. For the global lookup, lastpit+1 is used, hence
1923 // we use lastpit+2 here.
1924 DocIterator it = par_iterator_begin();
1925 DocIterator outerScope = it;
1926 outerScope.pit() = outerScope.lastpit() + 2;
1927 updateMacros(it, outerScope);
1931 void Buffer::updateMacroInstances() const
1933 LYXERR(Debug::MACROS, "updateMacroInstances for "
1934 << d->filename.onlyFileName());
1935 DocIterator it = doc_iterator_begin(inset());
1936 DocIterator end = doc_iterator_end(inset());
1937 for (; it != end; it.forwardPos()) {
1938 // look for MathData cells in InsetMathNest insets
1939 Inset * inset = it.nextInset();
1943 InsetMath * minset = inset->asInsetMath();
1947 // update macro in all cells of the InsetMathNest
1948 DocIterator::idx_type n = minset->nargs();
1949 MacroContext mc = MacroContext(*this, it);
1950 for (DocIterator::idx_type i = 0; i < n; ++i) {
1951 MathData & data = minset->cell(i);
1952 data.updateMacros(0, mc);
1958 void Buffer::listMacroNames(MacroNameSet & macros) const
1963 d->macro_lock = true;
1965 // loop over macro names
1966 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1967 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1968 for (; nameIt != nameEnd; ++nameIt)
1969 macros.insert(nameIt->first);
1971 // loop over children
1972 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1973 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1974 for (; it != end; ++it)
1975 it->first->listMacroNames(macros);
1978 if (d->parent_buffer)
1979 d->parent_buffer->listMacroNames(macros);
1981 d->macro_lock = false;
1985 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
1987 if (!d->parent_buffer)
1991 d->parent_buffer->listMacroNames(names);
1994 MacroNameSet::iterator it = names.begin();
1995 MacroNameSet::iterator end = names.end();
1996 for (; it != end; ++it) {
1998 MacroData const * data =
1999 d->parent_buffer->getMacro(*it, *this, false);
2001 macros.insert(data);
2003 // we cannot access the original MathMacroTemplate anymore
2004 // here to calls validate method. So we do its work here manually.
2005 // FIXME: somehow make the template accessible here.
2006 if (data->optionals() > 0)
2007 features.require("xargs");
2013 Buffer::References & Buffer::references(docstring const & label)
2015 if (d->parent_buffer)
2016 return const_cast<Buffer *>(masterBuffer())->references(label);
2018 RefCache::iterator it = d->ref_cache_.find(label);
2019 if (it != d->ref_cache_.end())
2020 return it->second.second;
2022 static InsetLabel const * dummy_il = 0;
2023 static References const dummy_refs;
2024 it = d->ref_cache_.insert(
2025 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2026 return it->second.second;
2030 Buffer::References const & Buffer::references(docstring const & label) const
2032 return const_cast<Buffer *>(this)->references(label);
2036 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2038 masterBuffer()->d->ref_cache_[label].first = il;
2042 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2044 return masterBuffer()->d->ref_cache_[label].first;
2048 void Buffer::clearReferenceCache() const
2050 if (!d->parent_buffer)
2051 d->ref_cache_.clear();
2055 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2058 //FIXME: This does not work for child documents yet.
2059 LASSERT(code == CITE_CODE, /**/);
2060 // Check if the label 'from' appears more than once
2061 vector<docstring> labels;
2063 BiblioInfo const & keys = masterBibInfo();
2064 BiblioInfo::const_iterator bit = keys.begin();
2065 BiblioInfo::const_iterator bend = keys.end();
2067 for (; bit != bend; ++bit)
2069 labels.push_back(bit->first);
2072 if (count(labels.begin(), labels.end(), from) > 1)
2075 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2076 if (it->lyxCode() == code) {
2077 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2078 docstring const oldValue = inset.getParam(paramName);
2079 if (oldValue == from)
2080 inset.setParam(paramName, to);
2086 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2087 pit_type par_end, bool full_source)
2089 OutputParams runparams(¶ms().encoding());
2090 runparams.nice = true;
2091 runparams.flavor = OutputParams::LATEX;
2092 runparams.linelen = lyxrc.plaintext_linelen;
2093 // No side effect of file copying and image conversion
2094 runparams.dryrun = true;
2098 os << "% " << _("Preview source code") << "\n\n";
2099 d->texrow.newline();
2100 d->texrow.newline();
2102 writeLaTeXSource(os, filePath(), runparams, true, true);
2104 writeDocBookSource(os, absFileName(), runparams, false);
2106 runparams.par_begin = par_begin;
2107 runparams.par_end = par_end;
2108 if (par_begin + 1 == par_end) {
2110 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2114 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2115 convert<docstring>(par_begin),
2116 convert<docstring>(par_end - 1))
2119 d->texrow.newline();
2120 d->texrow.newline();
2121 // output paragraphs
2123 latexParagraphs(*this, text(), os, d->texrow, runparams);
2126 docbookParagraphs(paragraphs(), *this, os, runparams);
2131 ErrorList & Buffer::errorList(string const & type) const
2133 static ErrorList emptyErrorList;
2134 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2135 if (I == d->errorLists.end())
2136 return emptyErrorList;
2142 void Buffer::structureChanged() const
2145 gui_->structureChanged();
2149 void Buffer::errors(string const & err) const
2156 void Buffer::message(docstring const & msg) const
2163 void Buffer::setBusy(bool on) const
2170 void Buffer::setReadOnly(bool on) const
2173 d->wa_->setReadOnly(on);
2177 void Buffer::updateTitles() const
2180 d->wa_->updateTitles();
2184 void Buffer::resetAutosaveTimers() const
2187 gui_->resetAutosaveTimers();
2191 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2200 class AutoSaveBuffer : public ForkedProcess {
2203 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2204 : buffer_(buffer), fname_(fname) {}
2206 virtual boost::shared_ptr<ForkedProcess> clone() const
2208 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2213 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2214 from_utf8(fname_.absFilename())));
2215 return run(DontWait);
2219 virtual int generateChild();
2221 Buffer const & buffer_;
2226 int AutoSaveBuffer::generateChild()
2228 // tmp_ret will be located (usually) in /tmp
2229 // will that be a problem?
2230 // Note that this calls ForkedCalls::fork(), so it's
2231 // ok cross-platform.
2232 pid_t const pid = fork();
2233 // If you want to debug the autosave
2234 // you should set pid to -1, and comment out the fork.
2235 if (pid != 0 && pid != -1)
2238 // pid = -1 signifies that lyx was unable
2239 // to fork. But we will do the save
2241 bool failed = false;
2242 FileName const tmp_ret = FileName::tempName("lyxauto");
2243 if (!tmp_ret.empty()) {
2244 buffer_.writeFile(tmp_ret);
2245 // assume successful write of tmp_ret
2246 if (!tmp_ret.moveTo(fname_))
2252 // failed to write/rename tmp_ret so try writing direct
2253 if (!buffer_.writeFile(fname_)) {
2254 // It is dangerous to do this in the child,
2255 // but safe in the parent, so...
2256 if (pid == -1) // emit message signal.
2257 buffer_.message(_("Autosave failed!"));
2261 if (pid == 0) // we are the child so...
2270 // Perfect target for a thread...
2271 void Buffer::autoSave() const
2273 if (isBakClean() || isReadonly()) {
2274 // We don't save now, but we'll try again later
2275 resetAutosaveTimers();
2279 // emit message signal.
2280 message(_("Autosaving current document..."));
2282 // create autosave filename
2283 string fname = filePath();
2285 fname += d->filename.onlyFileName();
2288 AutoSaveBuffer autosave(*this, FileName(fname));
2292 resetAutosaveTimers();
2296 string Buffer::bufferFormat() const
2306 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2307 string & result_file) const
2309 string backend_format;
2310 OutputParams runparams(¶ms().encoding());
2311 runparams.flavor = OutputParams::LATEX;
2312 runparams.linelen = lyxrc.plaintext_linelen;
2313 vector<string> backs = backends();
2314 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2315 // Get shortest path to format
2316 Graph::EdgePath path;
2317 for (vector<string>::const_iterator it = backs.begin();
2318 it != backs.end(); ++it) {
2319 Graph::EdgePath p = theConverters().getPath(*it, format);
2320 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2321 backend_format = *it;
2326 runparams.flavor = theConverters().getFlavor(path);
2328 Alert::error(_("Couldn't export file"),
2329 bformat(_("No information for exporting the format %1$s."),
2330 formats.prettyName(format)));
2334 backend_format = format;
2335 // FIXME: Don't hardcode format names here, but use a flag
2336 if (backend_format == "pdflatex")
2337 runparams.flavor = OutputParams::PDFLATEX;
2340 string filename = latexName(false);
2341 filename = addName(temppath(), filename);
2342 filename = changeExtension(filename,
2343 formats.extension(backend_format));
2346 updateMacroInstances();
2348 // Plain text backend
2349 if (backend_format == "text")
2350 writePlaintextFile(*this, FileName(filename), runparams);
2352 else if (backend_format == "lyx")
2353 writeFile(FileName(filename));
2355 else if (isDocBook()) {
2356 runparams.nice = !put_in_tempdir;
2357 makeDocBookFile(FileName(filename), runparams);
2360 else if (backend_format == format) {
2361 runparams.nice = true;
2362 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2364 } else if (!lyxrc.tex_allows_spaces
2365 && contains(filePath(), ' ')) {
2366 Alert::error(_("File name error"),
2367 _("The directory path to the document cannot contain spaces."));
2370 runparams.nice = false;
2371 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2375 string const error_type = (format == "program")
2376 ? "Build" : bufferFormat();
2377 string const ext = formats.extension(format);
2378 FileName const tmp_result_file(changeExtension(filename, ext));
2379 bool const success = theConverters().convert(this, FileName(filename),
2380 tmp_result_file, FileName(absFileName()), backend_format, format,
2381 errorList(error_type));
2382 // Emit the signal to show the error list.
2383 if (format != backend_format)
2388 if (put_in_tempdir) {
2389 result_file = tmp_result_file.absFilename();
2393 result_file = changeExtension(absFileName(), ext);
2394 // We need to copy referenced files (e. g. included graphics
2395 // if format == "dvi") to the result dir.
2396 vector<ExportedFile> const files =
2397 runparams.exportdata->externalFiles(format);
2398 string const dest = onlyPath(result_file);
2399 CopyStatus status = SUCCESS;
2400 for (vector<ExportedFile>::const_iterator it = files.begin();
2401 it != files.end() && status != CANCEL; ++it) {
2402 string const fmt = formats.getFormatFromFile(it->sourceName);
2403 status = copyFile(fmt, it->sourceName,
2404 makeAbsPath(it->exportName, dest),
2405 it->exportName, status == FORCE);
2407 if (status == CANCEL) {
2408 message(_("Document export cancelled."));
2409 } else if (tmp_result_file.exists()) {
2410 // Finally copy the main file
2411 status = copyFile(format, tmp_result_file,
2412 FileName(result_file), result_file,
2414 message(bformat(_("Document exported as %1$s "
2416 formats.prettyName(format),
2417 makeDisplayPath(result_file)));
2419 // This must be a dummy converter like fax (bug 1888)
2420 message(bformat(_("Document exported as %1$s"),
2421 formats.prettyName(format)));
2428 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2431 return doExport(format, put_in_tempdir, result_file);
2435 bool Buffer::preview(string const & format) const
2438 if (!doExport(format, true, result_file))
2440 return formats.view(*this, FileName(result_file), format);
2444 bool Buffer::isExportable(string const & format) const
2446 vector<string> backs = backends();
2447 for (vector<string>::const_iterator it = backs.begin();
2448 it != backs.end(); ++it)
2449 if (theConverters().isReachable(*it, format))
2455 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2457 vector<string> backs = backends();
2458 vector<Format const *> result =
2459 theConverters().getReachable(backs[0], only_viewable, true);
2460 for (vector<string>::const_iterator it = backs.begin() + 1;
2461 it != backs.end(); ++it) {
2462 vector<Format const *> r =
2463 theConverters().getReachable(*it, only_viewable, false);
2464 result.insert(result.end(), r.begin(), r.end());
2470 vector<string> Buffer::backends() const
2473 if (params().baseClass()->isTeXClassAvailable()) {
2474 v.push_back(bufferFormat());
2475 // FIXME: Don't hardcode format names here, but use a flag
2476 if (v.back() == "latex")
2477 v.push_back("pdflatex");
2479 v.push_back("text");
2485 bool Buffer::readFileHelper(FileName const & s)
2487 // File information about normal file
2489 docstring const file = makeDisplayPath(s.absFilename(), 50);
2490 docstring text = bformat(_("The specified document\n%1$s"
2491 "\ncould not be read."), file);
2492 Alert::error(_("Could not read document"), text);
2496 // Check if emergency save file exists and is newer.
2497 FileName const e(s.absFilename() + ".emergency");
2499 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2500 docstring const file = makeDisplayPath(s.absFilename(), 20);
2501 docstring const text =
2502 bformat(_("An emergency save of the document "
2504 "Recover emergency save?"), file);
2505 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2506 _("&Recover"), _("&Load Original"),
2510 // the file is not saved if we load the emergency file.
2520 // Now check if autosave file is newer.
2521 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2523 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2524 docstring const file = makeDisplayPath(s.absFilename(), 20);
2525 docstring const text =
2526 bformat(_("The backup of the document "
2527 "%1$s is newer.\n\nLoad the "
2528 "backup instead?"), file);
2529 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2530 _("&Load backup"), _("Load &original"),
2534 // the file is not saved if we load the autosave file.
2538 // Here we delete the autosave
2549 bool Buffer::loadLyXFile(FileName const & s)
2551 if (s.isReadableFile()) {
2552 if (readFileHelper(s)) {
2553 lyxvc().file_found_hook(s);
2554 if (!s.isWritable())
2559 docstring const file = makeDisplayPath(s.absFilename(), 20);
2560 // Here we probably should run
2561 if (LyXVC::file_not_found_hook(s)) {
2562 docstring const text =
2563 bformat(_("Do you want to retrieve the document"
2564 " %1$s from version control?"), file);
2565 int const ret = Alert::prompt(_("Retrieve from version control?"),
2566 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2569 // How can we know _how_ to do the checkout?
2570 // With the current VC support it has to be,
2571 // a RCS file since CVS do not have special ,v files.
2573 return loadLyXFile(s);
2581 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2583 TeXErrors::Errors::const_iterator cit = terr.begin();
2584 TeXErrors::Errors::const_iterator end = terr.end();
2586 for (; cit != end; ++cit) {
2589 int errorRow = cit->error_in_line;
2590 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2596 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2597 } while (found && id_start == id_end && pos_start == pos_end);
2599 errorList.push_back(ErrorItem(cit->error_desc,
2600 cit->error_text, id_start, pos_start, pos_end));