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 "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 373; // jspitzm: merge g-brief class
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer & parent, FileName const & file, bool readonly);
164 mutable TexRow texrow;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
191 mutable TocBackend toc_backend;
194 typedef pair<DocIterator, MacroData> ScopeMacro;
195 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197 /// map from the macro name to the position map,
198 /// which maps the macro definition position to the scope and the MacroData.
199 NamePositionScopeMacroMap macros;
202 /// positions of child buffers in the buffer
203 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206 /// position of children buffers in this buffer
207 BufferPositionMap children_positions;
208 /// map from children inclusion positions to their scope and their buffer
209 PositionScopeBufferMap position_to_children;
211 /// Container for all sort of Buffer dependant errors.
212 map<string, ErrorList> errorLists;
214 /// timestamp and checksum used to test if the file has been externally
215 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
217 unsigned long checksum_;
220 frontend::WorkAreaManager * wa_;
225 /// A cache for the bibfiles (including bibfiles of loaded child
226 /// documents), needed for appropriate update of natbib labels.
227 mutable support::FileNameList bibfilesCache_;
229 // FIXME The caching mechanism could be improved. At present, we have a
230 // cache for each Buffer, that caches all the bibliography info for that
231 // Buffer. A more efficient solution would be to have a global cache per
232 // file, and then to construct the Buffer's bibinfo from that.
233 /// A cache for bibliography info
234 mutable BiblioInfo bibinfo_;
235 /// whether the bibinfo cache is valid
236 bool bibinfoCacheValid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfileStatus_;
240 mutable RefCache ref_cache_;
242 /// our Text that should be wrapped in an InsetText
245 /// This is here to force the test to be done whenever parent_buffer
247 Buffer const * parent() const {
248 // if parent_buffer is not loaded, then it has been unloaded,
249 // which means that parent_buffer is an invalid pointer. So we
250 // set it to null in that case.
251 if (!theBufferList().isLoaded(parent_buffer))
253 return parent_buffer;
256 void setParent(Buffer const * pb) {
257 if (parent_buffer && pb && parent_buffer != pb)
258 LYXERR0("Warning: a buffer should not have two parents!");
262 /// So we can force access via the accessors.
263 mutable Buffer const * parent_buffer;
267 /// Creates the per buffer temporary directory
268 static FileName createBufferTmpDir()
271 // We are in our own directory. Why bother to mangle name?
272 // In fact I wrote this code to circumvent a problematic behaviour
273 // (bug?) of EMX mkstemp().
274 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
275 convert<string>(count++));
277 if (!tmpfl.createDirectory(0777)) {
278 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
279 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
280 from_utf8(tmpfl.absFilename())));
286 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
287 : lyx_clean(true), bak_clean(true), unnamed(false),
288 read_only(readonly_), filename(file), file_fully_loaded(false),
289 toc_backend(&parent), macro_lock(false), timestamp_(0),
290 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
293 temppath = createBufferTmpDir();
294 lyxvc.setBuffer(&parent);
296 wa_ = new frontend::WorkAreaManager;
300 Buffer::Buffer(string const & file, bool readonly)
301 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
303 LYXERR(Debug::INFO, "Buffer::Buffer()");
305 d->inset = new InsetText(this);
306 d->inset->setAutoBreakRows(true);
307 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
313 LYXERR(Debug::INFO, "Buffer::~Buffer()");
314 // here the buffer should take care that it is
315 // saved properly, before it goes into the void.
317 // GuiView already destroyed
321 // No need to do additional cleanups for internal buffer.
326 // loop over children
327 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
328 Impl::BufferPositionMap::iterator end = d->children_positions.end();
329 for (; it != end; ++it) {
330 Buffer * child = const_cast<Buffer *>(it->first);
331 // The child buffer might have been closed already.
332 if (theBufferList().isLoaded(child))
333 theBufferList().releaseChild(this, child);
337 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
338 msg += emergencyWrite();
339 frontend::Alert::warning(_("Attempting to close changed document!"), msg);
342 // clear references to children in macro tables
343 d->children_positions.clear();
344 d->position_to_children.clear();
346 if (!d->temppath.destroyDirectory()) {
347 Alert::warning(_("Could not remove temporary directory"),
348 bformat(_("Could not remove the temporary directory %1$s"),
349 from_utf8(d->temppath.absFilename())));
352 // Remove any previewed LaTeX snippets associated with this buffer.
353 thePreviews().removeLoader(*this);
359 void Buffer::changed() const
366 frontend::WorkAreaManager & Buffer::workAreaManager() const
368 LASSERT(d->wa_, /**/);
373 Text & Buffer::text() const
375 return d->inset->text();
379 Inset & Buffer::inset() const
385 BufferParams & Buffer::params()
391 BufferParams const & Buffer::params() const
397 ParagraphList & Buffer::paragraphs()
399 return text().paragraphs();
403 ParagraphList const & Buffer::paragraphs() const
405 return text().paragraphs();
409 LyXVC & Buffer::lyxvc()
415 LyXVC const & Buffer::lyxvc() const
421 string const Buffer::temppath() const
423 return d->temppath.absFilename();
427 TexRow & Buffer::texrow()
433 TexRow const & Buffer::texrow() const
439 TocBackend & Buffer::tocBackend() const
441 return d->toc_backend;
445 Undo & Buffer::undo()
451 string Buffer::latexName(bool const no_path) const
453 FileName latex_name =
454 makeLatexName(exportFileName());
455 return no_path ? latex_name.onlyFileName()
456 : latex_name.absFilename();
460 FileName Buffer::exportFileName() const
462 docstring const branch_suffix =
463 params().branchlist().getFilenameSuffix();
464 if (branch_suffix.empty())
467 string const name = fileName().onlyFileNameWithoutExt()
468 + to_utf8(branch_suffix);
469 FileName res(fileName().onlyPath().absFilename() + "/" + name);
470 res.changeExtension(fileName().extension());
476 string Buffer::logName(LogType * type) const
478 string const filename = latexName(false);
480 if (filename.empty()) {
486 string const path = temppath();
488 FileName const fname(addName(temppath(),
489 onlyFilename(changeExtension(filename,
492 // FIXME: how do we know this is the name of the build log?
493 FileName const bname(
494 addName(path, onlyFilename(
495 changeExtension(filename,
496 formats.extension(bufferFormat()) + ".out"))));
498 // Also consider the master buffer log file
499 FileName masterfname = fname;
501 if (masterBuffer() != this) {
502 string const mlogfile = masterBuffer()->logName(&mtype);
503 masterfname = FileName(mlogfile);
506 // If no Latex log or Build log is newer, show Build log
507 if (bname.exists() &&
508 ((!fname.exists() && !masterfname.exists())
509 || (fname.lastModified() < bname.lastModified()
510 && masterfname.lastModified() < bname.lastModified()))) {
511 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
514 return bname.absFilename();
515 // If we have a newer master file log or only a master log, show this
516 } else if (fname != masterfname
517 && (!fname.exists() && (masterfname.exists()
518 || fname.lastModified() < masterfname.lastModified()))) {
519 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
522 return masterfname.absFilename();
524 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
527 return fname.absFilename();
531 void Buffer::setReadonly(bool const flag)
533 if (d->read_only != flag) {
540 void Buffer::setFileName(string const & newfile)
542 d->filename = makeAbsPath(newfile);
543 setReadonly(d->filename.isReadOnly());
548 int Buffer::readHeader(Lexer & lex)
550 int unknown_tokens = 0;
552 int begin_header_line = -1;
554 // Initialize parameters that may be/go lacking in header:
555 params().branchlist().clear();
556 params().preamble.erase();
557 params().options.erase();
558 params().master.erase();
559 params().float_placement.erase();
560 params().paperwidth.erase();
561 params().paperheight.erase();
562 params().leftmargin.erase();
563 params().rightmargin.erase();
564 params().topmargin.erase();
565 params().bottommargin.erase();
566 params().headheight.erase();
567 params().headsep.erase();
568 params().footskip.erase();
569 params().columnsep.erase();
570 params().fontsCJK.erase();
571 params().listings_params.clear();
572 params().clearLayoutModules();
573 params().clearRemovedModules();
574 params().pdfoptions().clear();
575 params().indiceslist().clear();
576 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
578 for (int i = 0; i < 4; ++i) {
579 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
580 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
583 ErrorList & errorList = d->errorLists["Parse"];
592 if (token == "\\end_header")
596 if (token == "\\begin_header") {
597 begin_header_line = line;
601 LYXERR(Debug::PARSER, "Handling document header token: `"
604 string unknown = params().readToken(lex, token, d->filename.onlyPath());
605 if (!unknown.empty()) {
606 if (unknown[0] != '\\' && token == "\\textclass") {
607 Alert::warning(_("Unknown document class"),
608 bformat(_("Using the default document class, because the "
609 "class %1$s is unknown."), from_utf8(unknown)));
612 docstring const s = bformat(_("Unknown token: "
616 errorList.push_back(ErrorItem(_("Document header error"),
621 if (begin_header_line) {
622 docstring const s = _("\\begin_header is missing");
623 errorList.push_back(ErrorItem(_("Document header error"),
627 params().makeDocumentClass();
629 return unknown_tokens;
634 // changed to be public and have one parameter
635 // Returns true if "\end_document" is not read (Asger)
636 bool Buffer::readDocument(Lexer & lex)
638 ErrorList & errorList = d->errorLists["Parse"];
641 if (!lex.checkFor("\\begin_document")) {
642 docstring const s = _("\\begin_document is missing");
643 errorList.push_back(ErrorItem(_("Document header error"),
647 // we are reading in a brand new document
648 LASSERT(paragraphs().empty(), /**/);
652 if (params().outputChanges) {
653 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
654 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
655 LaTeXFeatures::isAvailable("xcolor");
657 if (!dvipost && !xcolorulem) {
658 Alert::warning(_("Changes not shown in LaTeX output"),
659 _("Changes will not be highlighted in LaTeX output, "
660 "because neither dvipost nor xcolor/ulem are installed.\n"
661 "Please install these packages or redefine "
662 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
663 } else if (!xcolorulem) {
664 Alert::warning(_("Changes not shown in LaTeX output"),
665 _("Changes will not be highlighted in LaTeX output "
666 "when using pdflatex, because xcolor and ulem are not installed.\n"
667 "Please install both packages or redefine "
668 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
672 if (!params().master.empty()) {
673 FileName const master_file = makeAbsPath(params().master,
674 onlyPath(absFileName()));
675 if (isLyXFilename(master_file.absFilename())) {
677 checkAndLoadLyXFile(master_file, true);
679 // necessary e.g. after a reload
680 // to re-register the child (bug 5873)
681 // FIXME: clean up updateMacros (here, only
682 // child registering is needed).
683 master->updateMacros();
684 // set master as master buffer, but only
685 // if we are a real child
686 if (master->isChild(this))
688 // if the master is not fully loaded
689 // it is probably just loading this
690 // child. No warning needed then.
691 else if (master->isFullyLoaded())
692 LYXERR0("The master '"
694 << "' assigned to this document ("
696 << ") does not include "
697 "this document. Ignoring the master assignment.");
702 // assure we have a default index
703 params().indiceslist().addDefault(B_("Index"));
706 bool const res = text().read(lex, errorList, d->inset);
710 updateMacroInstances();
715 bool Buffer::readString(string const & s)
717 params().compressed = false;
719 // remove dummy empty par
720 paragraphs().clear();
724 FileName const name = FileName::tempName("Buffer_readString");
725 switch (readFile(lex, name, true)) {
729 // We need to call lyx2lyx, so write the input to a file
730 ofstream os(name.toFilesystemEncoding().c_str());
733 return readFile(name);
743 bool Buffer::readFile(FileName const & filename)
745 FileName fname(filename);
747 params().compressed = fname.isZippedFile();
749 // remove dummy empty par
750 paragraphs().clear();
753 if (readFile(lex, fname) != success)
760 bool Buffer::isFullyLoaded() const
762 return d->file_fully_loaded;
766 void Buffer::setFullyLoaded(bool value)
768 d->file_fully_loaded = value;
772 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
775 LASSERT(!filename.empty(), /**/);
777 // the first (non-comment) token _must_ be...
778 if (!lex.checkFor("\\lyxformat")) {
779 Alert::error(_("Document format failure"),
780 bformat(_("%1$s is not a readable LyX document."),
781 from_utf8(filename.absFilename())));
787 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
788 // if present remove ".," from string.
789 size_t dot = tmp_format.find_first_of(".,");
790 //lyxerr << " dot found at " << dot << endl;
791 if (dot != string::npos)
792 tmp_format.erase(dot, 1);
793 int const file_format = convert<int>(tmp_format);
794 //lyxerr << "format: " << file_format << endl;
796 // save timestamp and checksum of the original disk file, making sure
797 // to not overwrite them with those of the file created in the tempdir
798 // when it has to be converted to the current format.
800 // Save the timestamp and checksum of disk file. If filename is an
801 // emergency file, save the timestamp and checksum of the original lyx file
802 // because isExternallyModified will check for this file. (BUG4193)
803 string diskfile = filename.absFilename();
804 if (suffixIs(diskfile, ".emergency"))
805 diskfile = diskfile.substr(0, diskfile.size() - 10);
806 saveCheckSum(FileName(diskfile));
809 if (file_format != LYX_FORMAT) {
812 // lyx2lyx would fail
815 FileName const tmpfile = FileName::tempName("Buffer_readFile");
816 if (tmpfile.empty()) {
817 Alert::error(_("Conversion failed"),
818 bformat(_("%1$s is from a different"
819 " version of LyX, but a temporary"
820 " file for converting it could"
822 from_utf8(filename.absFilename())));
825 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
826 if (lyx2lyx.empty()) {
827 Alert::error(_("Conversion script not found"),
828 bformat(_("%1$s is from a different"
829 " version of LyX, but the"
830 " conversion script lyx2lyx"
831 " could not be found."),
832 from_utf8(filename.absFilename())));
835 ostringstream command;
836 command << os::python()
837 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
838 << " -t " << convert<string>(LYX_FORMAT)
839 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
840 << ' ' << quoteName(filename.toFilesystemEncoding());
841 string const command_str = command.str();
843 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
845 cmd_ret const ret = runCommand(command_str);
846 if (ret.first != 0) {
847 Alert::error(_("Conversion script failed"),
848 bformat(_("%1$s is from a different version"
849 " of LyX, but the lyx2lyx script"
850 " failed to convert it."),
851 from_utf8(filename.absFilename())));
854 bool const ret = readFile(tmpfile);
855 // Do stuff with tmpfile name and buffer name here.
856 return ret ? success : failure;
861 if (readDocument(lex)) {
862 Alert::error(_("Document format failure"),
863 bformat(_("%1$s ended unexpectedly, which means"
864 " that it is probably corrupted."),
865 from_utf8(filename.absFilename())));
868 d->file_fully_loaded = true;
873 // Should probably be moved to somewhere else: BufferView? LyXView?
874 bool Buffer::save() const
876 // We don't need autosaves in the immediate future. (Asger)
877 resetAutosaveTimers();
879 string const encodedFilename = d->filename.toFilesystemEncoding();
882 bool madeBackup = false;
884 // make a backup if the file already exists
885 if (lyxrc.make_backup && fileName().exists()) {
886 backupName = FileName(absFileName() + '~');
887 if (!lyxrc.backupdir_path.empty()) {
888 string const mangledName =
889 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
890 backupName = FileName(addName(lyxrc.backupdir_path,
893 if (fileName().copyTo(backupName)) {
896 Alert::error(_("Backup failure"),
897 bformat(_("Cannot create backup file %1$s.\n"
898 "Please check whether the directory exists and is writeable."),
899 from_utf8(backupName.absFilename())));
900 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
904 // ask if the disk file has been externally modified (use checksum method)
905 if (fileName().exists() && isExternallyModified(checksum_method)) {
906 docstring const file = makeDisplayPath(absFileName(), 20);
907 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
908 "you want to overwrite this file?"), file);
909 int const ret = Alert::prompt(_("Overwrite modified file?"),
910 text, 1, 1, _("&Overwrite"), _("&Cancel"));
915 if (writeFile(d->filename)) {
919 // Saving failed, so backup is not backup
921 backupName.moveTo(d->filename);
927 bool Buffer::writeFile(FileName const & fname) const
929 if (d->read_only && fname == d->filename)
934 docstring const str = bformat(_("Saving document %1$s..."),
935 makeDisplayPath(fname.absFilename()));
938 if (params().compressed) {
939 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
940 retval = ofs && write(ofs);
942 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
943 retval = ofs && write(ofs);
947 message(str + _(" could not write file!"));
951 removeAutosaveFile();
953 saveCheckSum(d->filename);
954 message(str + _(" done."));
960 docstring Buffer::emergencyWrite()
962 // No need to save if the buffer has not changed.
966 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
968 docstring user_message = bformat(
969 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
971 // We try to save three places:
972 // 1) Same place as document. Unless it is an unnamed doc.
974 string s = absFileName();
977 if (writeFile(FileName(s))) {
979 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
982 user_message += _(" Save failed! Trying again...\n");
986 // 2) In HOME directory.
987 string s = addName(package().home_dir().absFilename(), absFileName());
989 lyxerr << ' ' << s << endl;
990 if (writeFile(FileName(s))) {
992 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
996 user_message += _(" Save failed! Trying yet again...\n");
998 // 3) In "/tmp" directory.
999 // MakeAbsPath to prepend the current
1000 // drive letter on OS/2
1001 s = addName(package().temp_dir().absFilename(), absFileName());
1003 lyxerr << ' ' << s << endl;
1004 if (writeFile(FileName(s))) {
1006 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1007 return user_message;
1010 user_message += _(" Save failed! Bummer. Document is lost.");
1013 return user_message;
1017 bool Buffer::write(ostream & ofs) const
1020 // Use the standard "C" locale for file output.
1021 ofs.imbue(locale::classic());
1024 // The top of the file should not be written by params().
1026 // write out a comment in the top of the file
1027 ofs << "#LyX " << lyx_version
1028 << " created this file. For more info see http://www.lyx.org/\n"
1029 << "\\lyxformat " << LYX_FORMAT << "\n"
1030 << "\\begin_document\n";
1032 /// For each author, set 'used' to true if there is a change
1033 /// by this author in the document; otherwise set it to 'false'.
1034 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1035 AuthorList::Authors::const_iterator a_end = params().authors().end();
1036 for (; a_it != a_end; ++a_it)
1037 a_it->setUsed(false);
1039 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1040 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1041 for ( ; it != end; ++it)
1042 it->checkAuthors(params().authors());
1044 // now write out the buffer parameters.
1045 ofs << "\\begin_header\n";
1046 params().writeFile(ofs);
1047 ofs << "\\end_header\n";
1050 ofs << "\n\\begin_body\n";
1052 ofs << "\n\\end_body\n";
1054 // Write marker that shows file is complete
1055 ofs << "\\end_document" << endl;
1057 // Shouldn't really be needed....
1060 // how to check if close went ok?
1061 // Following is an attempt... (BE 20001011)
1063 // good() returns false if any error occured, including some
1064 // formatting error.
1065 // bad() returns true if something bad happened in the buffer,
1066 // which should include file system full errors.
1071 lyxerr << "File was not closed properly." << endl;
1078 bool Buffer::makeLaTeXFile(FileName const & fname,
1079 string const & original_path,
1080 OutputParams const & runparams_in,
1081 bool output_preamble, bool output_body) const
1083 OutputParams runparams = runparams_in;
1084 if (params().useXetex)
1085 runparams.flavor = OutputParams::XETEX;
1087 string const encoding = runparams.encoding->iconvName();
1088 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1091 try { ofs.reset(encoding); }
1092 catch (iconv_codecvt_facet_exception & e) {
1093 lyxerr << "Caught iconv exception: " << e.what() << endl;
1094 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1095 "verify that the support software for your encoding (%1$s) is "
1096 "properly installed"), from_ascii(encoding)));
1099 if (!openFileWrite(ofs, fname))
1102 //TexStream ts(ofs.rdbuf(), &texrow());
1103 ErrorList & errorList = d->errorLists["Export"];
1105 bool failed_export = false;
1108 writeLaTeXSource(ofs, original_path,
1109 runparams, output_preamble, output_body);
1111 catch (EncodingException & e) {
1112 odocstringstream ods;
1113 ods.put(e.failed_char);
1115 oss << "0x" << hex << e.failed_char << dec;
1116 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1117 " (code point %2$s)"),
1118 ods.str(), from_utf8(oss.str()));
1119 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1120 "representable in the chosen encoding.\n"
1121 "Changing the document encoding to utf8 could help."),
1122 e.par_id, e.pos, e.pos + 1));
1123 failed_export = true;
1125 catch (iconv_codecvt_facet_exception & e) {
1126 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1127 _(e.what()), -1, 0, 0));
1128 failed_export = true;
1130 catch (exception const & e) {
1131 errorList.push_back(ErrorItem(_("conversion failed"),
1132 _(e.what()), -1, 0, 0));
1133 failed_export = true;
1136 lyxerr << "Caught some really weird exception..." << endl;
1142 failed_export = true;
1143 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1147 return !failed_export;
1151 void Buffer::writeLaTeXSource(odocstream & os,
1152 string const & original_path,
1153 OutputParams const & runparams_in,
1154 bool const output_preamble, bool const output_body) const
1156 // The child documents, if any, shall be already loaded at this point.
1158 OutputParams runparams = runparams_in;
1160 // Classify the unicode characters appearing in math insets
1161 Encodings::initUnicodeMath(*this);
1163 // validate the buffer.
1164 LYXERR(Debug::LATEX, " Validating buffer...");
1165 LaTeXFeatures features(*this, params(), runparams);
1167 LYXERR(Debug::LATEX, " Buffer validation done.");
1169 // The starting paragraph of the coming rows is the
1170 // first paragraph of the document. (Asger)
1171 if (output_preamble && runparams.nice) {
1172 os << "%% LyX " << lyx_version << " created this file. "
1173 "For more info, see http://www.lyx.org/.\n"
1174 "%% Do not edit unless you really know what "
1176 d->texrow.newline();
1177 d->texrow.newline();
1179 LYXERR(Debug::INFO, "lyx document header finished");
1181 // Don't move this behind the parent_buffer=0 code below,
1182 // because then the macros will not get the right "redefinition"
1183 // flag as they don't see the parent macros which are output before.
1186 // fold macros if possible, still with parent buffer as the
1187 // macros will be put in the prefix anyway.
1188 updateMacroInstances();
1190 // There are a few differences between nice LaTeX and usual files:
1191 // usual is \batchmode and has a
1192 // special input@path to allow the including of figures
1193 // with either \input or \includegraphics (what figinsets do).
1194 // input@path is set when the actual parameter
1195 // original_path is set. This is done for usual tex-file, but not
1196 // for nice-latex-file. (Matthias 250696)
1197 // Note that input@path is only needed for something the user does
1198 // in the preamble, included .tex files or ERT, files included by
1199 // LyX work without it.
1200 if (output_preamble) {
1201 if (!runparams.nice) {
1202 // code for usual, NOT nice-latex-file
1203 os << "\\batchmode\n"; // changed
1204 // from \nonstopmode
1205 d->texrow.newline();
1207 if (!original_path.empty()) {
1209 // We don't know the encoding of inputpath
1210 docstring const inputpath = from_utf8(latex_path(original_path));
1211 os << "\\makeatletter\n"
1212 << "\\def\\input@path{{"
1213 << inputpath << "/}}\n"
1214 << "\\makeatother\n";
1215 d->texrow.newline();
1216 d->texrow.newline();
1217 d->texrow.newline();
1220 // get parent macros (if this buffer has a parent) which will be
1221 // written at the document begin further down.
1222 MacroSet parentMacros;
1223 listParentMacros(parentMacros, features);
1225 // Write the preamble
1226 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1228 runparams.use_japanese = features.isRequired("japanese");
1234 os << "\\begin{document}\n";
1235 d->texrow.newline();
1237 // output the parent macros
1238 MacroSet::iterator it = parentMacros.begin();
1239 MacroSet::iterator end = parentMacros.end();
1240 for (; it != end; ++it)
1241 (*it)->write(os, true);
1242 } // output_preamble
1244 d->texrow.start(paragraphs().begin()->id(), 0);
1246 LYXERR(Debug::INFO, "preamble finished, now the body.");
1248 // if we are doing a real file with body, even if this is the
1249 // child of some other buffer, let's cut the link here.
1250 // This happens for example if only a child document is printed.
1251 Buffer const * save_parent = 0;
1252 if (output_preamble) {
1253 save_parent = d->parent();
1258 latexParagraphs(*this, text(), os, d->texrow, runparams);
1260 // Restore the parenthood if needed
1261 if (output_preamble)
1262 d->setParent(save_parent);
1264 // add this just in case after all the paragraphs
1266 d->texrow.newline();
1268 if (output_preamble) {
1269 os << "\\end{document}\n";
1270 d->texrow.newline();
1271 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1273 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1275 runparams_in.encoding = runparams.encoding;
1277 // Just to be sure. (Asger)
1278 d->texrow.newline();
1280 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1281 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1285 bool Buffer::isLatex() const
1287 return params().documentClass().outputType() == LATEX;
1291 bool Buffer::isLiterate() const
1293 return params().documentClass().outputType() == LITERATE;
1297 bool Buffer::isDocBook() const
1299 return params().documentClass().outputType() == DOCBOOK;
1303 void Buffer::makeDocBookFile(FileName const & fname,
1304 OutputParams const & runparams,
1305 bool const body_only) const
1307 LYXERR(Debug::LATEX, "makeDocBookFile...");
1310 if (!openFileWrite(ofs, fname))
1313 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1317 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1321 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1322 OutputParams const & runparams,
1323 bool const only_body) const
1325 LaTeXFeatures features(*this, params(), runparams);
1330 DocumentClass const & tclass = params().documentClass();
1331 string const top_element = tclass.latexname();
1334 if (runparams.flavor == OutputParams::XML)
1335 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1338 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1341 if (! tclass.class_header().empty())
1342 os << from_ascii(tclass.class_header());
1343 else if (runparams.flavor == OutputParams::XML)
1344 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1345 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1347 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1349 docstring preamble = from_utf8(params().preamble);
1350 if (runparams.flavor != OutputParams::XML ) {
1351 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1352 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1353 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1354 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1357 string const name = runparams.nice
1358 ? changeExtension(absFileName(), ".sgml") : fname;
1359 preamble += features.getIncludedFiles(name);
1360 preamble += features.getLyXSGMLEntities();
1362 if (!preamble.empty()) {
1363 os << "\n [ " << preamble << " ]";
1368 string top = top_element;
1370 if (runparams.flavor == OutputParams::XML)
1371 top += params().language->code();
1373 top += params().language->code().substr(0, 2);
1376 if (!params().options.empty()) {
1378 top += params().options;
1381 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1382 << " file was created by LyX " << lyx_version
1383 << "\n See http://www.lyx.org/ for more information -->\n";
1385 params().documentClass().counters().reset();
1389 sgml::openTag(os, top);
1391 docbookParagraphs(text(), *this, os, runparams);
1392 sgml::closeTag(os, top_element);
1396 void Buffer::makeLyXHTMLFile(FileName const & fname,
1397 OutputParams const & runparams,
1398 bool const body_only) const
1400 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1403 if (!openFileWrite(ofs, fname))
1406 writeLyXHTMLSource(ofs, runparams, body_only);
1410 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1414 void Buffer::writeLyXHTMLSource(odocstream & os,
1415 OutputParams const & runparams,
1416 bool const only_body) const
1418 LaTeXFeatures features(*this, params(), runparams);
1420 // We are going to use some of this stuff ourselves,
1421 // so make sure it is up to date.
1427 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1428 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n";
1429 // FIXME Language should be set properly.
1430 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1433 // FIXME Presumably need to set this right
1434 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1435 // FIXME Get this during validation? What about other meta-data?
1436 os << "<title>TBA</title>\n";
1438 os << "\n<!-- Text Class Preamble -->\n"
1439 << features.getTClassHTMLPreamble()
1440 << "\n<!-- Premable Snippets -->\n"
1441 << from_utf8(features.getPreambleSnippets());
1443 os << "\n<!-- Layout-provided Styles -->\n";
1444 docstring const styleinfo = features.getTClassHTMLStyles();
1445 if (!styleinfo.empty()) {
1446 os << "<style type='text/css'>\n"
1450 os << "</head>\n<body>\n";
1454 params().documentClass().counters().reset();
1455 xhtmlParagraphs(text(), *this, xs, runparams);
1457 os << "</body>\n</html>\n";
1461 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1462 // Other flags: -wall -v0 -x
1463 int Buffer::runChktex()
1467 // get LaTeX-Filename
1468 FileName const path(temppath());
1469 string const name = addName(path.absFilename(), latexName());
1470 string const org_path = filePath();
1472 PathChanger p(path); // path to LaTeX file
1473 message(_("Running chktex..."));
1475 // Generate the LaTeX file if neccessary
1476 OutputParams runparams(¶ms().encoding());
1477 runparams.flavor = OutputParams::LATEX;
1478 runparams.nice = false;
1479 makeLaTeXFile(FileName(name), org_path, runparams);
1482 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1483 int const res = chktex.run(terr); // run chktex
1486 Alert::error(_("chktex failure"),
1487 _("Could not run chktex successfully."));
1488 } else if (res > 0) {
1489 ErrorList & errlist = d->errorLists["ChkTeX"];
1491 bufferErrors(terr, errlist);
1502 void Buffer::validate(LaTeXFeatures & features) const
1504 params().validate(features);
1508 for_each(paragraphs().begin(), paragraphs().end(),
1509 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1511 if (lyxerr.debugging(Debug::LATEX)) {
1512 features.showStruct();
1517 void Buffer::getLabelList(vector<docstring> & list) const
1519 // If this is a child document, use the parent's list instead.
1520 Buffer const * const pbuf = d->parent();
1522 pbuf->getLabelList(list);
1527 Toc & toc = d->toc_backend.toc("label");
1528 TocIterator toc_it = toc.begin();
1529 TocIterator end = toc.end();
1530 for (; toc_it != end; ++toc_it) {
1531 if (toc_it->depth() == 0)
1532 list.push_back(toc_it->str());
1537 void Buffer::updateBibfilesCache(UpdateScope scope) const
1539 // If this is a child document, use the parent's cache instead.
1540 Buffer const * const pbuf = d->parent();
1541 if (pbuf && scope != UpdateChildOnly) {
1542 pbuf->updateBibfilesCache();
1546 d->bibfilesCache_.clear();
1547 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1548 if (it->lyxCode() == BIBTEX_CODE) {
1549 InsetBibtex const & inset =
1550 static_cast<InsetBibtex const &>(*it);
1551 support::FileNameList const bibfiles = inset.getBibFiles();
1552 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1555 } else if (it->lyxCode() == INCLUDE_CODE) {
1556 InsetInclude & inset =
1557 static_cast<InsetInclude &>(*it);
1558 inset.updateBibfilesCache();
1559 support::FileNameList const & bibfiles =
1560 inset.getBibfilesCache();
1561 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1566 // the bibinfo cache is now invalid
1567 d->bibinfoCacheValid_ = false;
1571 void Buffer::invalidateBibinfoCache()
1573 d->bibinfoCacheValid_ = false;
1577 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1579 // If this is a child document, use the parent's cache instead.
1580 Buffer const * const pbuf = d->parent();
1581 if (pbuf && scope != UpdateChildOnly)
1582 return pbuf->getBibfilesCache();
1584 // We update the cache when first used instead of at loading time.
1585 if (d->bibfilesCache_.empty())
1586 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1588 return d->bibfilesCache_;
1592 BiblioInfo const & Buffer::masterBibInfo() const
1594 // if this is a child document and the parent is already loaded
1595 // use the parent's list instead [ale990412]
1596 Buffer const * const tmp = masterBuffer();
1599 return tmp->masterBibInfo();
1600 return localBibInfo();
1604 BiblioInfo const & Buffer::localBibInfo() const
1606 if (d->bibinfoCacheValid_) {
1607 support::FileNameList const & bibfilesCache = getBibfilesCache();
1608 // compare the cached timestamps with the actual ones.
1609 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1610 support::FileNameList::const_iterator en = bibfilesCache.end();
1611 for (; ei != en; ++ ei) {
1612 time_t lastw = ei->lastModified();
1613 if (lastw != d->bibfileStatus_[*ei]) {
1614 d->bibinfoCacheValid_ = false;
1615 d->bibfileStatus_[*ei] = lastw;
1621 if (!d->bibinfoCacheValid_) {
1622 d->bibinfo_.clear();
1623 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1624 it->fillWithBibKeys(d->bibinfo_, it);
1625 d->bibinfoCacheValid_ = true;
1631 bool Buffer::isDepClean(string const & name) const
1633 DepClean::const_iterator const it = d->dep_clean.find(name);
1634 if (it == d->dep_clean.end())
1640 void Buffer::markDepClean(string const & name)
1642 d->dep_clean[name] = true;
1646 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1649 // FIXME? if there is an Buffer LFUN that can be dispatched even
1650 // if internal, put a switch '(cmd.action)' here.
1656 switch (cmd.action) {
1658 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1659 flag.setOnOff(isReadonly());
1662 // FIXME: There is need for a command-line import.
1663 //case LFUN_BUFFER_IMPORT:
1665 case LFUN_BUFFER_AUTO_SAVE:
1668 case LFUN_BUFFER_EXPORT_CUSTOM:
1669 // FIXME: Nothing to check here?
1672 case LFUN_BUFFER_EXPORT: {
1673 docstring const arg = cmd.argument();
1674 enable = arg == "custom" || isExportable(to_utf8(arg));
1676 flag.message(bformat(
1677 _("Don't know how to export to format: %1$s"), arg));
1681 case LFUN_MASTER_BUFFER_UPDATE:
1682 case LFUN_MASTER_BUFFER_VIEW:
1683 enable = parent() != 0;
1685 case LFUN_BUFFER_UPDATE:
1686 case LFUN_BUFFER_VIEW: {
1687 string format = to_utf8(cmd.argument());
1688 if (cmd.argument().empty())
1689 format = getDefaultOutputFormat();
1690 typedef vector<Format const *> Formats;
1692 formats = exportableFormats(true);
1693 Formats::const_iterator fit = formats.begin();
1694 Formats::const_iterator end = formats.end();
1696 for (; fit != end ; ++fit) {
1697 if ((*fit)->name() == format)
1702 case LFUN_BUFFER_CHKTEX:
1703 enable = isLatex() && !lyxrc.chktex_command.empty();
1706 case LFUN_BUILD_PROGRAM:
1707 enable = isExportable("program");
1710 case LFUN_BRANCH_ACTIVATE:
1711 case LFUN_BRANCH_DEACTIVATE: {
1712 BranchList const & branchList = params().branchlist();
1713 docstring const branchName = cmd.argument();
1714 enable = !branchName.empty() && branchList.find(branchName);
1718 case LFUN_BRANCH_ADD:
1719 case LFUN_BRANCHES_RENAME:
1720 case LFUN_BUFFER_PRINT:
1721 // if no Buffer is present, then of course we won't be called!
1724 case LFUN_BUFFER_LANGUAGE:
1725 enable = !isReadonly();
1731 flag.setEnabled(enable);
1736 void Buffer::dispatch(string const & command, DispatchResult & result)
1738 return dispatch(lyxaction.lookupFunc(command), result);
1742 // NOTE We can end up here even if we have no GUI, because we are called
1743 // by LyX::exec to handled command-line requests. So we may need to check
1744 // whether we have a GUI or not. The boolean use_gui holds this information.
1745 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1748 // FIXME? if there is an Buffer LFUN that can be dispatched even
1749 // if internal, put a switch '(cmd.action)' here.
1750 dr.dispatched(false);
1753 string const argument = to_utf8(func.argument());
1754 // We'll set this back to false if need be.
1755 bool dispatched = true;
1756 undo().beginUndoGroup();
1758 switch (func.action) {
1759 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1760 if (lyxvc().inUse())
1761 lyxvc().toggleReadOnly();
1763 setReadonly(!isReadonly());
1766 case LFUN_BUFFER_EXPORT: {
1767 if (argument == "custom") {
1768 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
1771 bool success = doExport(argument, false);
1772 dr.setError(success);
1774 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1779 case LFUN_BUFFER_UPDATE: {
1780 string format = argument;
1781 if (argument.empty())
1782 format = getDefaultOutputFormat();
1783 doExport(format, true);
1787 case LFUN_BUFFER_VIEW: {
1788 string format = argument;
1789 if (argument.empty())
1790 format = getDefaultOutputFormat();
1795 case LFUN_MASTER_BUFFER_UPDATE: {
1796 string format = argument;
1797 if (argument.empty())
1798 format = masterBuffer()->getDefaultOutputFormat();
1799 masterBuffer()->doExport(format, true);
1803 case LFUN_MASTER_BUFFER_VIEW: {
1804 string format = argument;
1805 if (argument.empty())
1806 format = masterBuffer()->getDefaultOutputFormat();
1807 masterBuffer()->preview(format);
1811 case LFUN_BUILD_PROGRAM:
1812 doExport("program", true);
1815 case LFUN_BUFFER_CHKTEX:
1819 case LFUN_BUFFER_EXPORT_CUSTOM: {
1821 string command = split(argument, format_name, ' ');
1822 Format const * format = formats.getFormat(format_name);
1824 lyxerr << "Format \"" << format_name
1825 << "\" not recognized!"
1830 // The name of the file created by the conversion process
1833 // Output to filename
1834 if (format->name() == "lyx") {
1835 string const latexname = latexName(false);
1836 filename = changeExtension(latexname,
1837 format->extension());
1838 filename = addName(temppath(), filename);
1840 if (!writeFile(FileName(filename)))
1844 doExport(format_name, true, filename);
1847 // Substitute $$FName for filename
1848 if (!contains(command, "$$FName"))
1849 command = "( " + command + " ) < $$FName";
1850 command = subst(command, "$$FName", filename);
1852 // Execute the command in the background
1854 call.startscript(Systemcall::DontWait, command);
1858 // FIXME: There is need for a command-line import.
1860 case LFUN_BUFFER_IMPORT:
1865 case LFUN_BUFFER_AUTO_SAVE:
1869 case LFUN_BRANCH_ADD: {
1870 docstring const branch_name = func.argument();
1871 if (branch_name.empty()) {
1875 BranchList & branch_list = params().branchlist();
1876 Branch * branch = branch_list.find(branch_name);
1878 LYXERR0("Branch " << branch_name << " already exists.");
1880 docstring const msg =
1881 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1884 branch_list.add(branch_name);
1885 branch = branch_list.find(branch_name);
1886 string const x11hexname = X11hexname(branch->color());
1887 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1888 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1890 dr.update(Update::Force);
1895 case LFUN_BRANCH_ACTIVATE:
1896 case LFUN_BRANCH_DEACTIVATE: {
1897 BranchList & branchList = params().branchlist();
1898 docstring const branchName = func.argument();
1899 // the case without a branch name is handled elsewhere
1900 if (branchName.empty()) {
1904 Branch * branch = branchList.find(branchName);
1906 LYXERR0("Branch " << branchName << " does not exist.");
1908 docstring const msg =
1909 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1912 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1914 dr.update(Update::Force);
1919 case LFUN_BRANCHES_RENAME: {
1920 if (func.argument().empty())
1923 docstring const oldname = from_utf8(func.getArg(0));
1924 docstring const newname = from_utf8(func.getArg(1));
1925 InsetIterator it = inset_iterator_begin(inset());
1926 InsetIterator const end = inset_iterator_end(inset());
1927 bool success = false;
1928 for (; it != end; ++it) {
1929 if (it->lyxCode() == BRANCH_CODE) {
1930 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1931 if (ins.branch() == oldname) {
1932 undo().recordUndo(it);
1933 ins.rename(newname);
1938 if (it->lyxCode() == INCLUDE_CODE) {
1939 // get buffer of external file
1940 InsetInclude const & ins =
1941 static_cast<InsetInclude const &>(*it);
1942 Buffer * child = ins.getChildBuffer();
1945 child->dispatch(func, dr);
1950 dr.update(Update::Force);
1954 case LFUN_BUFFER_PRINT: {
1955 // we'll assume there's a problem until we succeed
1957 string target = func.getArg(0);
1958 string target_name = func.getArg(1);
1959 string command = func.getArg(2);
1962 || target_name.empty()
1963 || command.empty()) {
1964 LYXERR0("Unable to parse " << func.argument());
1965 docstring const msg =
1966 bformat(_("Unable to parse \"%1$s\""), func.argument());
1970 if (target != "printer" && target != "file") {
1971 LYXERR0("Unrecognized target \"" << target << '"');
1972 docstring const msg =
1973 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1978 if (!doExport("dvi", true)) {
1979 showPrintError(absFileName());
1980 dr.setMessage(_("Error exporting to DVI."));
1984 // Push directory path.
1985 string const path = temppath();
1986 // Prevent the compiler from optimizing away p
1990 // there are three cases here:
1991 // 1. we print to a file
1992 // 2. we print directly to a printer
1993 // 3. we print using a spool command (print to file first)
1996 string const dviname = changeExtension(latexName(true), "dvi");
1998 if (target == "printer") {
1999 if (!lyxrc.print_spool_command.empty()) {
2000 // case 3: print using a spool
2001 string const psname = changeExtension(dviname,".ps");
2002 command += ' ' + lyxrc.print_to_file
2005 + quoteName(dviname);
2007 string command2 = lyxrc.print_spool_command + ' ';
2008 if (target_name != "default") {
2009 command2 += lyxrc.print_spool_printerprefix
2013 command2 += quoteName(psname);
2015 // If successful, then spool command
2016 res = one.startscript(Systemcall::Wait, command);
2019 // If there's no GUI, we have to wait on this command. Otherwise,
2020 // LyX deletes the temporary directory, and with it the spooled
2021 // file, before it can be printed!!
2022 Systemcall::Starttype stype = use_gui ?
2023 Systemcall::DontWait : Systemcall::Wait;
2024 res = one.startscript(stype, command2);
2027 // case 2: print directly to a printer
2028 if (target_name != "default")
2029 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2031 Systemcall::Starttype stype = use_gui ?
2032 Systemcall::DontWait : Systemcall::Wait;
2033 res = one.startscript(stype, command + quoteName(dviname));
2037 // case 1: print to a file
2038 FileName const filename(makeAbsPath(target_name, filePath()));
2039 FileName const dvifile(makeAbsPath(dviname, path));
2040 if (filename.exists()) {
2041 docstring text = bformat(
2042 _("The file %1$s already exists.\n\n"
2043 "Do you want to overwrite that file?"),
2044 makeDisplayPath(filename.absFilename()));
2045 if (Alert::prompt(_("Overwrite file?"),
2046 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2049 command += ' ' + lyxrc.print_to_file
2050 + quoteName(filename.toFilesystemEncoding())
2052 + quoteName(dvifile.toFilesystemEncoding());
2054 Systemcall::Starttype stype = use_gui ?
2055 Systemcall::DontWait : Systemcall::Wait;
2056 res = one.startscript(stype, command);
2062 dr.setMessage(_("Error running external commands."));
2063 showPrintError(absFileName());
2068 case LFUN_BUFFER_LANGUAGE: {
2069 Language const * oldL = params().language;
2070 Language const * newL = languages.getLanguage(argument);
2071 if (!newL || oldL == newL)
2073 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2074 changeLanguage(oldL, newL);
2082 dr.dispatched(dispatched);
2083 undo().endUndoGroup();
2087 void Buffer::changeLanguage(Language const * from, Language const * to)
2089 LASSERT(from, /**/);
2092 for_each(par_iterator_begin(),
2094 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2098 bool Buffer::isMultiLingual() const
2100 ParConstIterator end = par_iterator_end();
2101 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2102 if (it->isMultiLingual(params()))
2109 DocIterator Buffer::getParFromID(int const id) const
2111 Buffer * buf = const_cast<Buffer *>(this);
2113 // John says this is called with id == -1 from undo
2114 lyxerr << "getParFromID(), id: " << id << endl;
2115 return doc_iterator_end(buf);
2118 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2119 if (it.paragraph().id() == id)
2122 return doc_iterator_end(buf);
2126 bool Buffer::hasParWithID(int const id) const
2128 return !getParFromID(id).atEnd();
2132 ParIterator Buffer::par_iterator_begin()
2134 return ParIterator(doc_iterator_begin(this));
2138 ParIterator Buffer::par_iterator_end()
2140 return ParIterator(doc_iterator_end(this));
2144 ParConstIterator Buffer::par_iterator_begin() const
2146 return ParConstIterator(doc_iterator_begin(this));
2150 ParConstIterator Buffer::par_iterator_end() const
2152 return ParConstIterator(doc_iterator_end(this));
2156 Language const * Buffer::language() const
2158 return params().language;
2162 docstring const Buffer::B_(string const & l10n) const
2164 return params().B_(l10n);
2168 bool Buffer::isClean() const
2170 return d->lyx_clean;
2174 bool Buffer::isBakClean() const
2176 return d->bak_clean;
2180 bool Buffer::isExternallyModified(CheckMethod method) const
2182 LASSERT(d->filename.exists(), /**/);
2183 // if method == timestamp, check timestamp before checksum
2184 return (method == checksum_method
2185 || d->timestamp_ != d->filename.lastModified())
2186 && d->checksum_ != d->filename.checksum();
2190 void Buffer::saveCheckSum(FileName const & file) const
2192 if (file.exists()) {
2193 d->timestamp_ = file.lastModified();
2194 d->checksum_ = file.checksum();
2196 // in the case of save to a new file.
2203 void Buffer::markClean() const
2205 if (!d->lyx_clean) {
2206 d->lyx_clean = true;
2209 // if the .lyx file has been saved, we don't need an
2211 d->bak_clean = true;
2215 void Buffer::markBakClean() const
2217 d->bak_clean = true;
2221 void Buffer::setUnnamed(bool flag)
2227 bool Buffer::isUnnamed() const
2234 /// Don't check unnamed, here: isInternal() is used in
2235 /// newBuffer(), where the unnamed flag has not been set by anyone
2236 /// yet. Also, for an internal buffer, there should be no need for
2237 /// retrieving fileName() nor for checking if it is unnamed or not.
2238 bool Buffer::isInternal() const
2240 return fileName().extension() == "internal";
2244 void Buffer::markDirty()
2247 d->lyx_clean = false;
2250 d->bak_clean = false;
2252 DepClean::iterator it = d->dep_clean.begin();
2253 DepClean::const_iterator const end = d->dep_clean.end();
2255 for (; it != end; ++it)
2260 FileName Buffer::fileName() const
2266 string Buffer::absFileName() const
2268 return d->filename.absFilename();
2272 string Buffer::filePath() const
2274 return d->filename.onlyPath().absFilename() + "/";
2278 bool Buffer::isReadonly() const
2280 return d->read_only;
2284 void Buffer::setParent(Buffer const * buffer)
2286 // Avoids recursive include.
2287 d->setParent(buffer == this ? 0 : buffer);
2292 Buffer const * Buffer::parent() const
2298 void Buffer::collectRelatives(BufferSet & bufs) const
2302 parent()->collectRelatives(bufs);
2304 // loop over children
2305 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2306 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2307 for (; it != end; ++it)
2308 bufs.insert(const_cast<Buffer *>(it->first));
2312 std::vector<Buffer const *> Buffer::allRelatives() const
2315 collectRelatives(bufs);
2316 BufferSet::iterator it = bufs.begin();
2317 std::vector<Buffer const *> ret;
2318 for (; it != bufs.end(); ++it)
2324 Buffer const * Buffer::masterBuffer() const
2326 Buffer const * const pbuf = d->parent();
2330 return pbuf->masterBuffer();
2334 bool Buffer::isChild(Buffer * child) const
2336 return d->children_positions.find(child) != d->children_positions.end();
2340 DocIterator Buffer::firstChildPosition(Buffer const * child)
2342 Impl::BufferPositionMap::iterator it;
2343 it = d->children_positions.find(child);
2344 if (it == d->children_positions.end())
2345 return DocIterator(this);
2350 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2352 std::vector<Buffer *> clist;
2353 // loop over children
2354 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2355 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2356 for (; it != end; ++it) {
2357 Buffer * child = const_cast<Buffer *>(it->first);
2358 clist.push_back(child);
2359 if (grand_children) {
2360 // there might be grandchildren
2361 std::vector<Buffer *> glist = child->getChildren();
2362 for (vector<Buffer *>::const_iterator git = glist.begin();
2363 git != glist.end(); ++git)
2364 clist.push_back(*git);
2371 template<typename M>
2372 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2377 typename M::iterator it = m.lower_bound(x);
2378 if (it == m.begin())
2386 MacroData const * Buffer::getBufferMacro(docstring const & name,
2387 DocIterator const & pos) const
2389 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2391 // if paragraphs have no macro context set, pos will be empty
2395 // we haven't found anything yet
2396 DocIterator bestPos = par_iterator_begin();
2397 MacroData const * bestData = 0;
2399 // find macro definitions for name
2400 Impl::NamePositionScopeMacroMap::iterator nameIt
2401 = d->macros.find(name);
2402 if (nameIt != d->macros.end()) {
2403 // find last definition in front of pos or at pos itself
2404 Impl::PositionScopeMacroMap::const_iterator it
2405 = greatest_below(nameIt->second, pos);
2406 if (it != nameIt->second.end()) {
2408 // scope ends behind pos?
2409 if (pos < it->second.first) {
2410 // Looks good, remember this. If there
2411 // is no external macro behind this,
2412 // we found the right one already.
2413 bestPos = it->first;
2414 bestData = &it->second.second;
2418 // try previous macro if there is one
2419 if (it == nameIt->second.begin())
2426 // find macros in included files
2427 Impl::PositionScopeBufferMap::const_iterator it
2428 = greatest_below(d->position_to_children, pos);
2429 if (it == d->position_to_children.end())
2430 // no children before
2434 // do we know something better (i.e. later) already?
2435 if (it->first < bestPos )
2438 // scope ends behind pos?
2439 if (pos < it->second.first) {
2440 // look for macro in external file
2441 d->macro_lock = true;
2442 MacroData const * data
2443 = it->second.second->getMacro(name, false);
2444 d->macro_lock = false;
2446 bestPos = it->first;
2452 // try previous file if there is one
2453 if (it == d->position_to_children.begin())
2458 // return the best macro we have found
2463 MacroData const * Buffer::getMacro(docstring const & name,
2464 DocIterator const & pos, bool global) const
2469 // query buffer macros
2470 MacroData const * data = getBufferMacro(name, pos);
2474 // If there is a master buffer, query that
2475 Buffer const * const pbuf = d->parent();
2477 d->macro_lock = true;
2478 MacroData const * macro = pbuf->getMacro(
2479 name, *this, false);
2480 d->macro_lock = false;
2486 data = MacroTable::globalMacros().get(name);
2495 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2497 // set scope end behind the last paragraph
2498 DocIterator scope = par_iterator_begin();
2499 scope.pit() = scope.lastpit() + 1;
2501 return getMacro(name, scope, global);
2505 MacroData const * Buffer::getMacro(docstring const & name,
2506 Buffer const & child, bool global) const
2508 // look where the child buffer is included first
2509 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2510 if (it == d->children_positions.end())
2513 // check for macros at the inclusion position
2514 return getMacro(name, it->second, global);
2518 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2520 pit_type lastpit = it.lastpit();
2522 // look for macros in each paragraph
2523 while (it.pit() <= lastpit) {
2524 Paragraph & par = it.paragraph();
2526 // iterate over the insets of the current paragraph
2527 InsetList const & insets = par.insetList();
2528 InsetList::const_iterator iit = insets.begin();
2529 InsetList::const_iterator end = insets.end();
2530 for (; iit != end; ++iit) {
2531 it.pos() = iit->pos;
2533 // is it a nested text inset?
2534 if (iit->inset->asInsetText()) {
2535 // Inset needs its own scope?
2536 InsetText const * itext = iit->inset->asInsetText();
2537 bool newScope = itext->isMacroScope();
2539 // scope which ends just behind the inset
2540 DocIterator insetScope = it;
2543 // collect macros in inset
2544 it.push_back(CursorSlice(*iit->inset));
2545 updateMacros(it, newScope ? insetScope : scope);
2550 // is it an external file?
2551 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2552 // get buffer of external file
2553 InsetInclude const & inset =
2554 static_cast<InsetInclude const &>(*iit->inset);
2555 d->macro_lock = true;
2556 Buffer * child = inset.getChildBuffer();
2557 d->macro_lock = false;
2561 // register its position, but only when it is
2562 // included first in the buffer
2563 if (d->children_positions.find(child) ==
2564 d->children_positions.end())
2565 d->children_positions[child] = it;
2567 // register child with its scope
2568 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2572 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2576 MathMacroTemplate & macroTemplate =
2577 static_cast<MathMacroTemplate &>(*iit->inset);
2578 MacroContext mc(this, it);
2579 macroTemplate.updateToContext(mc);
2582 bool valid = macroTemplate.validMacro();
2583 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2584 // then the BufferView's cursor will be invalid in
2585 // some cases which leads to crashes.
2590 // FIXME (Abdel), I don't understandt why we pass 'it' here
2591 // instead of 'macroTemplate' defined above... is this correct?
2592 d->macros[macroTemplate.name()][it] =
2593 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2603 void Buffer::updateMacros() const
2608 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2610 // start with empty table
2612 d->children_positions.clear();
2613 d->position_to_children.clear();
2615 // Iterate over buffer, starting with first paragraph
2616 // The scope must be bigger than any lookup DocIterator
2617 // later. For the global lookup, lastpit+1 is used, hence
2618 // we use lastpit+2 here.
2619 DocIterator it = par_iterator_begin();
2620 DocIterator outerScope = it;
2621 outerScope.pit() = outerScope.lastpit() + 2;
2622 updateMacros(it, outerScope);
2626 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2628 InsetIterator it = inset_iterator_begin(inset());
2629 InsetIterator const end = inset_iterator_end(inset());
2630 for (; it != end; ++it) {
2631 if (it->lyxCode() == BRANCH_CODE) {
2632 InsetBranch & br = static_cast<InsetBranch &>(*it);
2633 docstring const name = br.branch();
2634 if (!from_master && !params().branchlist().find(name))
2635 result.push_back(name);
2636 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2637 result.push_back(name);
2640 if (it->lyxCode() == INCLUDE_CODE) {
2641 // get buffer of external file
2642 InsetInclude const & ins =
2643 static_cast<InsetInclude const &>(*it);
2644 Buffer * child = ins.getChildBuffer();
2647 child->getUsedBranches(result, true);
2650 // remove duplicates
2655 void Buffer::updateMacroInstances() const
2657 LYXERR(Debug::MACROS, "updateMacroInstances for "
2658 << d->filename.onlyFileName());
2659 DocIterator it = doc_iterator_begin(this);
2661 DocIterator const end = doc_iterator_end(this);
2662 for (; it != end; it.forwardInset()) {
2663 // look for MathData cells in InsetMathNest insets
2664 InsetMath * minset = it.nextInset()->asInsetMath();
2668 // update macro in all cells of the InsetMathNest
2669 DocIterator::idx_type n = minset->nargs();
2670 MacroContext mc = MacroContext(this, it);
2671 for (DocIterator::idx_type i = 0; i < n; ++i) {
2672 MathData & data = minset->cell(i);
2673 data.updateMacros(0, mc);
2679 void Buffer::listMacroNames(MacroNameSet & macros) const
2684 d->macro_lock = true;
2686 // loop over macro names
2687 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2688 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2689 for (; nameIt != nameEnd; ++nameIt)
2690 macros.insert(nameIt->first);
2692 // loop over children
2693 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2694 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2695 for (; it != end; ++it)
2696 it->first->listMacroNames(macros);
2699 Buffer const * const pbuf = d->parent();
2701 pbuf->listMacroNames(macros);
2703 d->macro_lock = false;
2707 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2709 Buffer const * const pbuf = d->parent();
2714 pbuf->listMacroNames(names);
2717 MacroNameSet::iterator it = names.begin();
2718 MacroNameSet::iterator end = names.end();
2719 for (; it != end; ++it) {
2721 MacroData const * data =
2722 pbuf->getMacro(*it, *this, false);
2724 macros.insert(data);
2726 // we cannot access the original MathMacroTemplate anymore
2727 // here to calls validate method. So we do its work here manually.
2728 // FIXME: somehow make the template accessible here.
2729 if (data->optionals() > 0)
2730 features.require("xargs");
2736 Buffer::References & Buffer::references(docstring const & label)
2739 return const_cast<Buffer *>(masterBuffer())->references(label);
2741 RefCache::iterator it = d->ref_cache_.find(label);
2742 if (it != d->ref_cache_.end())
2743 return it->second.second;
2745 static InsetLabel const * dummy_il = 0;
2746 static References const dummy_refs;
2747 it = d->ref_cache_.insert(
2748 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2749 return it->second.second;
2753 Buffer::References const & Buffer::references(docstring const & label) const
2755 return const_cast<Buffer *>(this)->references(label);
2759 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2761 masterBuffer()->d->ref_cache_[label].first = il;
2765 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2767 return masterBuffer()->d->ref_cache_[label].first;
2771 void Buffer::clearReferenceCache() const
2774 d->ref_cache_.clear();
2778 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2781 //FIXME: This does not work for child documents yet.
2782 LASSERT(code == CITE_CODE, /**/);
2783 // Check if the label 'from' appears more than once
2784 vector<docstring> labels;
2786 BiblioInfo const & keys = masterBibInfo();
2787 BiblioInfo::const_iterator bit = keys.begin();
2788 BiblioInfo::const_iterator bend = keys.end();
2790 for (; bit != bend; ++bit)
2792 labels.push_back(bit->first);
2795 if (count(labels.begin(), labels.end(), from) > 1)
2798 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2799 if (it->lyxCode() == code) {
2800 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2801 docstring const oldValue = inset.getParam(paramName);
2802 if (oldValue == from)
2803 inset.setParam(paramName, to);
2809 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2810 pit_type par_end, bool full_source) const
2812 OutputParams runparams(¶ms().encoding());
2813 runparams.nice = true;
2814 runparams.flavor = params().useXetex ?
2815 OutputParams::XETEX : OutputParams::LATEX;
2816 runparams.linelen = lyxrc.plaintext_linelen;
2817 // No side effect of file copying and image conversion
2818 runparams.dryrun = true;
2821 os << "% " << _("Preview source code") << "\n\n";
2823 d->texrow.newline();
2824 d->texrow.newline();
2826 writeDocBookSource(os, absFileName(), runparams, false);
2828 // latex or literate
2829 writeLaTeXSource(os, string(), runparams, true, true);
2831 runparams.par_begin = par_begin;
2832 runparams.par_end = par_end;
2833 if (par_begin + 1 == par_end) {
2835 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2839 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2840 convert<docstring>(par_begin),
2841 convert<docstring>(par_end - 1))
2848 // output paragraphs
2850 docbookParagraphs(text(), *this, os, runparams);
2852 // latex or literate
2853 latexParagraphs(*this, text(), os, texrow, runparams);
2858 ErrorList & Buffer::errorList(string const & type) const
2860 static ErrorList emptyErrorList;
2861 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2862 if (I == d->errorLists.end())
2863 return emptyErrorList;
2869 void Buffer::updateTocItem(std::string const & type,
2870 DocIterator const & dit) const
2873 gui_->updateTocItem(type, dit);
2877 void Buffer::structureChanged() const
2880 gui_->structureChanged();
2884 void Buffer::errors(string const & err, bool from_master) const
2887 gui_->errors(err, from_master);
2891 void Buffer::message(docstring const & msg) const
2898 void Buffer::setBusy(bool on) const
2905 void Buffer::setReadOnly(bool on) const
2908 d->wa_->setReadOnly(on);
2912 void Buffer::updateTitles() const
2915 d->wa_->updateTitles();
2919 void Buffer::resetAutosaveTimers() const
2922 gui_->resetAutosaveTimers();
2926 bool Buffer::hasGuiDelegate() const
2932 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2941 class AutoSaveBuffer : public ForkedProcess {
2944 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2945 : buffer_(buffer), fname_(fname) {}
2947 virtual boost::shared_ptr<ForkedProcess> clone() const
2949 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2954 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2955 from_utf8(fname_.absFilename())));
2956 return run(DontWait);
2960 virtual int generateChild();
2962 Buffer const & buffer_;
2967 int AutoSaveBuffer::generateChild()
2969 #if defined(__APPLE__)
2970 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
2971 * We should use something else like threads.
2973 * Since I do not know how to determine at run time what is the OS X
2974 * version, I just disable forking altogether for now (JMarc)
2976 pid_t const pid = -1;
2978 // tmp_ret will be located (usually) in /tmp
2979 // will that be a problem?
2980 // Note that this calls ForkedCalls::fork(), so it's
2981 // ok cross-platform.
2982 pid_t const pid = fork();
2983 // If you want to debug the autosave
2984 // you should set pid to -1, and comment out the fork.
2985 if (pid != 0 && pid != -1)
2989 // pid = -1 signifies that lyx was unable
2990 // to fork. But we will do the save
2992 bool failed = false;
2993 FileName const tmp_ret = FileName::tempName("lyxauto");
2994 if (!tmp_ret.empty()) {
2995 buffer_.writeFile(tmp_ret);
2996 // assume successful write of tmp_ret
2997 if (!tmp_ret.moveTo(fname_))
3003 // failed to write/rename tmp_ret so try writing direct
3004 if (!buffer_.writeFile(fname_)) {
3005 // It is dangerous to do this in the child,
3006 // but safe in the parent, so...
3007 if (pid == -1) // emit message signal.
3008 buffer_.message(_("Autosave failed!"));
3012 if (pid == 0) // we are the child so...
3021 FileName Buffer::getAutosaveFilename() const
3023 // if the document is unnamed try to save in the backup dir, else
3024 // in the default document path, and as a last try in the filePath,
3025 // which will most often be the temporary directory
3028 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3029 : lyxrc.backupdir_path;
3030 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3033 string const fname = "#" + d->filename.onlyFileName() + "#";
3034 return makeAbsPath(fname, fpath);
3038 void Buffer::removeAutosaveFile() const
3040 FileName const f = getAutosaveFilename();
3046 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3048 FileName const newauto = getAutosaveFilename();
3049 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3050 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3054 // Perfect target for a thread...
3055 void Buffer::autoSave() const
3057 if (isBakClean() || isReadonly()) {
3058 // We don't save now, but we'll try again later
3059 resetAutosaveTimers();
3063 // emit message signal.
3064 message(_("Autosaving current document..."));
3065 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3069 resetAutosaveTimers();
3073 string Buffer::bufferFormat() const
3075 string format = params().documentClass().outputFormat();
3076 if (format == "latex") {
3077 if (params().useXetex)
3079 if (params().encoding().package() == Encoding::japanese)
3086 string Buffer::getDefaultOutputFormat() const
3088 if (!params().defaultOutputFormat.empty()
3089 && params().defaultOutputFormat != "default")
3090 return params().defaultOutputFormat;
3091 typedef vector<Format const *> Formats;
3092 Formats formats = exportableFormats(true);
3095 || params().useXetex
3096 || params().encoding().package() == Encoding::japanese) {
3097 if (formats.empty())
3099 // return the first we find
3100 return formats.front()->name();
3102 return lyxrc.default_view_format;
3107 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3108 string & result_file) const
3110 string backend_format;
3111 OutputParams runparams(¶ms().encoding());
3112 runparams.flavor = OutputParams::LATEX;
3113 runparams.linelen = lyxrc.plaintext_linelen;
3114 vector<string> backs = backends();
3115 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3116 // Get shortest path to format
3117 Graph::EdgePath path;
3118 for (vector<string>::const_iterator it = backs.begin();
3119 it != backs.end(); ++it) {
3120 Graph::EdgePath p = theConverters().getPath(*it, format);
3121 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3122 backend_format = *it;
3127 runparams.flavor = theConverters().getFlavor(path);
3129 Alert::error(_("Couldn't export file"),
3130 bformat(_("No information for exporting the format %1$s."),
3131 formats.prettyName(format)));
3135 backend_format = format;
3136 // FIXME: Don't hardcode format names here, but use a flag
3137 if (backend_format == "pdflatex")
3138 runparams.flavor = OutputParams::PDFLATEX;
3141 string filename = latexName(false);
3142 filename = addName(temppath(), filename);
3143 filename = changeExtension(filename,
3144 formats.extension(backend_format));
3147 updateMacroInstances();
3149 // Plain text backend
3150 if (backend_format == "text") {
3151 runparams.flavor = OutputParams::TEXT;
3152 writePlaintextFile(*this, FileName(filename), runparams);
3155 else if (backend_format == "xhtml") {
3156 runparams.flavor = OutputParams::HTML;
3157 makeLyXHTMLFile(FileName(filename), runparams);
3158 } else if (backend_format == "lyx")
3159 writeFile(FileName(filename));
3161 else if (isDocBook()) {
3162 runparams.nice = !put_in_tempdir;
3163 makeDocBookFile(FileName(filename), runparams);
3166 else if (backend_format == format) {
3167 runparams.nice = true;
3168 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3170 } else if (!lyxrc.tex_allows_spaces
3171 && contains(filePath(), ' ')) {
3172 Alert::error(_("File name error"),
3173 _("The directory path to the document cannot contain spaces."));
3176 runparams.nice = false;
3177 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3181 string const error_type = (format == "program")
3182 ? "Build" : bufferFormat();
3183 ErrorList & error_list = d->errorLists[error_type];
3184 string const ext = formats.extension(format);
3185 FileName const tmp_result_file(changeExtension(filename, ext));
3186 bool const success = theConverters().convert(this, FileName(filename),
3187 tmp_result_file, FileName(absFileName()), backend_format, format,
3189 // Emit the signal to show the error list.
3190 if (format != backend_format) {
3192 // also to the children, in case of master-buffer-view
3193 std::vector<Buffer *> clist = getChildren();
3194 for (vector<Buffer *>::const_iterator cit = clist.begin();
3195 cit != clist.end(); ++cit)
3196 (*cit)->errors(error_type, true);
3201 if (put_in_tempdir) {
3202 result_file = tmp_result_file.absFilename();
3206 result_file = changeExtension(exportFileName().absFilename(), ext);
3207 // We need to copy referenced files (e. g. included graphics
3208 // if format == "dvi") to the result dir.
3209 vector<ExportedFile> const files =
3210 runparams.exportdata->externalFiles(format);
3211 string const dest = onlyPath(result_file);
3212 CopyStatus status = SUCCESS;
3213 for (vector<ExportedFile>::const_iterator it = files.begin();
3214 it != files.end() && status != CANCEL; ++it) {
3215 string const fmt = formats.getFormatFromFile(it->sourceName);
3216 status = copyFile(fmt, it->sourceName,
3217 makeAbsPath(it->exportName, dest),
3218 it->exportName, status == FORCE);
3220 if (status == CANCEL) {
3221 message(_("Document export cancelled."));
3222 } else if (tmp_result_file.exists()) {
3223 // Finally copy the main file
3224 status = copyFile(format, tmp_result_file,
3225 FileName(result_file), result_file,
3227 message(bformat(_("Document exported as %1$s "
3229 formats.prettyName(format),
3230 makeDisplayPath(result_file)));
3232 // This must be a dummy converter like fax (bug 1888)
3233 message(bformat(_("Document exported as %1$s"),
3234 formats.prettyName(format)));
3241 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3244 return doExport(format, put_in_tempdir, result_file);
3248 bool Buffer::preview(string const & format) const
3251 if (!doExport(format, true, result_file))
3253 return formats.view(*this, FileName(result_file), format);
3257 bool Buffer::isExportable(string const & format) const
3259 vector<string> backs = backends();
3260 for (vector<string>::const_iterator it = backs.begin();
3261 it != backs.end(); ++it)
3262 if (theConverters().isReachable(*it, format))
3268 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3270 vector<string> const backs = backends();
3271 vector<Format const *> result =
3272 theConverters().getReachable(backs[0], only_viewable, true);
3273 for (vector<string>::const_iterator it = backs.begin() + 1;
3274 it != backs.end(); ++it) {
3275 vector<Format const *> r =
3276 theConverters().getReachable(*it, only_viewable, false);
3277 result.insert(result.end(), r.begin(), r.end());
3283 vector<string> Buffer::backends() const
3286 v.push_back(bufferFormat());
3287 // FIXME: Don't hardcode format names here, but use a flag
3288 if (v.back() == "latex")
3289 v.push_back("pdflatex");
3290 v.push_back("xhtml");
3291 v.push_back("text");
3297 bool Buffer::readFileHelper(FileName const & s)
3299 // File information about normal file
3301 docstring const file = makeDisplayPath(s.absFilename(), 50);
3302 docstring text = bformat(_("The specified document\n%1$s"
3303 "\ncould not be read."), file);
3304 Alert::error(_("Could not read document"), text);
3308 // Check if emergency save file exists and is newer.
3309 FileName const e(s.absFilename() + ".emergency");
3311 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3312 docstring const file = makeDisplayPath(s.absFilename(), 20);
3313 docstring const text =
3314 bformat(_("An emergency save of the document "
3316 "Recover emergency save?"), file);
3317 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3318 _("&Recover"), _("&Load Original"),
3322 // the file is not saved if we load the emergency file.
3327 if ((res = readFile(e)) == success)
3328 str = _("Document was successfully recovered.");
3330 str = _("Document was NOT successfully recovered.");
3331 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3332 from_utf8(e.absFilename()));
3334 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3335 _("&Remove"), _("&Keep it"))) {
3338 Alert::warning(_("Emergency file deleted"),
3339 _("Do not forget to save your file now!"), true);
3344 if (!Alert::prompt(_("Delete emergency file?"),
3345 _("Remove emergency file now?"), 1, 1,
3346 _("&Remove"), _("&Keep it")))
3354 // Now check if autosave file is newer.
3355 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3357 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3358 docstring const file = makeDisplayPath(s.absFilename(), 20);
3359 docstring const text =
3360 bformat(_("The backup of the document "
3361 "%1$s is newer.\n\nLoad the "
3362 "backup instead?"), file);
3363 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3364 _("&Load backup"), _("Load &original"),
3368 // the file is not saved if we load the autosave file.
3372 // Here we delete the autosave
3383 bool Buffer::loadLyXFile(FileName const & s)
3385 if (s.isReadableFile()) {
3386 if (readFileHelper(s)) {
3387 lyxvc().file_found_hook(s);
3388 if (!s.isWritable())
3393 docstring const file = makeDisplayPath(s.absFilename(), 20);
3394 // Here we probably should run
3395 if (LyXVC::file_not_found_hook(s)) {
3396 docstring const text =
3397 bformat(_("Do you want to retrieve the document"
3398 " %1$s from version control?"), file);
3399 int const ret = Alert::prompt(_("Retrieve from version control?"),
3400 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3403 // How can we know _how_ to do the checkout?
3404 // With the current VC support it has to be,
3405 // a RCS file since CVS do not have special ,v files.
3407 return loadLyXFile(s);
3415 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3417 TeXErrors::Errors::const_iterator cit = terr.begin();
3418 TeXErrors::Errors::const_iterator end = terr.end();
3420 for (; cit != end; ++cit) {
3423 int errorRow = cit->error_in_line;
3424 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3430 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3431 } while (found && id_start == id_end && pos_start == pos_end);
3433 errorList.push_back(ErrorItem(cit->error_desc,
3434 cit->error_text, id_start, pos_start, pos_end));
3439 void Buffer::setBuffersForInsets() const
3441 inset().setBuffer(const_cast<Buffer &>(*this));
3445 void Buffer::updateLabels(bool out, UpdateScope scope) const
3447 // Use the master text class also for child documents
3448 Buffer const * const master = masterBuffer();
3449 DocumentClass const & textclass = master->params().documentClass();
3451 // keep the buffers to be children in this set. If the call from the
3452 // master comes back we can see which of them were actually seen (i.e.
3453 // via an InsetInclude). The remaining ones in the set need still be updated.
3454 static std::set<Buffer const *> bufToUpdate;
3455 if (scope == UpdateMaster) {
3456 // If this is a child document start with the master
3457 if (master != this) {
3458 bufToUpdate.insert(this);
3459 master->updateLabels(out);
3460 // Do this here in case the master has no gui associated with it. Then,
3461 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3465 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3466 if (bufToUpdate.find(this) == bufToUpdate.end())
3470 // start over the counters in the master
3471 textclass.counters().reset();
3474 // update will be done below for this buffer
3475 bufToUpdate.erase(this);
3477 // update all caches
3478 clearReferenceCache();
3481 Buffer & cbuf = const_cast<Buffer &>(*this);
3483 LASSERT(!text().paragraphs().empty(), /**/);
3486 ParIterator parit = cbuf.par_iterator_begin();
3487 updateLabels(parit, out);
3490 // TocBackend update will be done later.
3493 cbuf.tocBackend().update();
3494 if (scope == UpdateMaster)
3495 cbuf.structureChanged();
3499 static depth_type getDepth(DocIterator const & it)
3501 depth_type depth = 0;
3502 for (size_t i = 0 ; i < it.depth() ; ++i)
3503 if (!it[i].inset().inMathed())
3504 depth += it[i].paragraph().getDepth() + 1;
3505 // remove 1 since the outer inset does not count
3509 static depth_type getItemDepth(ParIterator const & it)
3511 Paragraph const & par = *it;
3512 LabelType const labeltype = par.layout().labeltype;
3514 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3517 // this will hold the lowest depth encountered up to now.
3518 depth_type min_depth = getDepth(it);
3519 ParIterator prev_it = it;
3522 --prev_it.top().pit();
3524 // start of nested inset: go to outer par
3526 if (prev_it.empty()) {
3527 // start of document: nothing to do
3532 // We search for the first paragraph with same label
3533 // that is not more deeply nested.
3534 Paragraph & prev_par = *prev_it;
3535 depth_type const prev_depth = getDepth(prev_it);
3536 if (labeltype == prev_par.layout().labeltype) {
3537 if (prev_depth < min_depth)
3538 return prev_par.itemdepth + 1;
3539 if (prev_depth == min_depth)
3540 return prev_par.itemdepth;
3542 min_depth = min(min_depth, prev_depth);
3543 // small optimization: if we are at depth 0, we won't
3544 // find anything else
3545 if (prev_depth == 0)
3551 static bool needEnumCounterReset(ParIterator const & it)
3553 Paragraph const & par = *it;
3554 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3555 depth_type const cur_depth = par.getDepth();
3556 ParIterator prev_it = it;
3557 while (prev_it.pit()) {
3558 --prev_it.top().pit();
3559 Paragraph const & prev_par = *prev_it;
3560 if (prev_par.getDepth() <= cur_depth)
3561 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3563 // start of nested inset: reset
3568 // set the label of a paragraph. This includes the counters.
3569 void Buffer::setLabel(ParIterator & it) const
3571 BufferParams const & bp = this->masterBuffer()->params();
3572 DocumentClass const & textclass = bp.documentClass();
3573 Paragraph & par = it.paragraph();
3574 Layout const & layout = par.layout();
3575 Counters & counters = textclass.counters();
3577 if (par.params().startOfAppendix()) {
3578 // FIXME: only the counter corresponding to toplevel
3579 // sectioning should be reset
3581 counters.appendix(true);
3583 par.params().appendix(counters.appendix());
3585 // Compute the item depth of the paragraph
3586 par.itemdepth = getItemDepth(it);
3588 if (layout.margintype == MARGIN_MANUAL
3589 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3590 if (par.params().labelWidthString().empty())
3591 par.params().labelWidthString(par.expandLabel(layout, bp));
3593 par.params().labelWidthString(docstring());
3596 switch(layout.labeltype) {
3598 if (layout.toclevel <= bp.secnumdepth
3599 && (layout.latextype != LATEX_ENVIRONMENT
3600 || it.text()->isFirstInSequence(it.pit()))) {
3601 counters.step(layout.counter);
3602 par.params().labelString(
3603 par.expandLabel(layout, bp));
3605 par.params().labelString(docstring());
3608 case LABEL_ITEMIZE: {
3609 // At some point of time we should do something more
3610 // clever here, like:
3611 // par.params().labelString(
3612 // bp.user_defined_bullet(par.itemdepth).getText());
3613 // for now, use a simple hardcoded label
3614 docstring itemlabel;
3615 switch (par.itemdepth) {
3617 itemlabel = char_type(0x2022);
3620 itemlabel = char_type(0x2013);
3623 itemlabel = char_type(0x2217);
3626 itemlabel = char_type(0x2219); // or 0x00b7
3629 par.params().labelString(itemlabel);
3633 case LABEL_ENUMERATE: {
3634 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3636 switch (par.itemdepth) {
3645 enumcounter += "iv";
3648 // not a valid enumdepth...
3652 // Maybe we have to reset the enumeration counter.
3653 if (needEnumCounterReset(it))
3654 counters.reset(enumcounter);
3655 counters.step(enumcounter);
3657 string const & lang = par.getParLanguage(bp)->code();
3658 par.params().labelString(counters.theCounter(enumcounter, lang));
3663 case LABEL_SENSITIVE: {
3664 string const & type = counters.current_float();
3665 docstring full_label;
3667 full_label = this->B_("Senseless!!! ");
3669 docstring name = this->B_(textclass.floats().getType(type).name());
3670 if (counters.hasCounter(from_utf8(type))) {
3671 string const & lang = par.getParLanguage(bp)->code();
3672 counters.step(from_utf8(type));
3673 full_label = bformat(from_ascii("%1$s %2$s:"),
3675 counters.theCounter(from_utf8(type), lang));
3677 full_label = bformat(from_ascii("%1$s #:"), name);
3679 par.params().labelString(full_label);
3683 case LABEL_NO_LABEL:
3684 par.params().labelString(docstring());
3688 case LABEL_TOP_ENVIRONMENT:
3689 case LABEL_CENTERED_TOP_ENVIRONMENT:
3692 par.params().labelString(par.expandLabel(layout, bp));
3698 void Buffer::updateLabels(ParIterator & parit, bool out) const
3700 LASSERT(parit.pit() == 0, /**/);
3702 // set the position of the text in the buffer to be able
3703 // to resolve macros in it. This has nothing to do with
3704 // labels, but by putting it here we avoid implementing
3705 // a whole bunch of traversal routines just for this call.
3706 parit.text()->setMacrocontextPosition(parit);
3708 depth_type maxdepth = 0;
3709 pit_type const lastpit = parit.lastpit();
3710 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3711 // reduce depth if necessary
3712 parit->params().depth(min(parit->params().depth(), maxdepth));
3713 maxdepth = parit->getMaxDepthAfter();
3715 // set the counter for this paragraph
3719 InsetList::const_iterator iit = parit->insetList().begin();
3720 InsetList::const_iterator end = parit->insetList().end();
3721 for (; iit != end; ++iit) {
3722 parit.pos() = iit->pos;
3723 iit->inset->updateLabels(parit, out);
3729 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3730 WordLangTuple & word_lang, docstring_list & suggestions) const
3734 suggestions.clear();
3735 word_lang = WordLangTuple();
3736 // OK, we start from here.
3737 DocIterator const end = doc_iterator_end(this);
3738 for (; from != end; from.forwardPos()) {
3739 // We are only interested in text so remove the math CursorSlice.
3740 while (from.inMathed())
3741 from.forwardInset();
3743 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {