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 = 374; // rgheck: HTML output options
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, Buffer const * cloned_buffer);
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 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
263 /// This one is useful for preview detached in a thread.
264 Buffer const * cloned_buffer_;
267 /// So we can force access via the accessors.
268 mutable Buffer const * parent_buffer;
273 /// Creates the per buffer temporary directory
274 static FileName createBufferTmpDir()
277 // We are in our own directory. Why bother to mangle name?
278 // In fact I wrote this code to circumvent a problematic behaviour
279 // (bug?) of EMX mkstemp().
280 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
281 convert<string>(count++));
283 if (!tmpfl.createDirectory(0777)) {
284 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
285 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
286 from_utf8(tmpfl.absFilename())));
292 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
293 Buffer const * cloned_buffer)
294 : lyx_clean(true), bak_clean(true), unnamed(false),
295 read_only(readonly_), filename(file), file_fully_loaded(false),
296 toc_backend(&parent), macro_lock(false), timestamp_(0),
297 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
298 cloned_buffer_(cloned_buffer), parent_buffer(0)
300 if (!cloned_buffer_) {
301 temppath = createBufferTmpDir();
302 lyxvc.setBuffer(&parent);
304 wa_ = new frontend::WorkAreaManager;
307 temppath = cloned_buffer_->d->temppath;
308 file_fully_loaded = true;
309 params = cloned_buffer_->d->params;
313 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
314 : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
316 LYXERR(Debug::INFO, "Buffer::Buffer()");
318 d->inset = new InsetText(*cloned_buffer->d->inset);
319 d->inset->setBuffer(*this);
320 // FIXME: optimize this loop somewhat, maybe by creating a new
321 // general recursive Inset::setId().
322 DocIterator it = doc_iterator_begin(this);
323 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
324 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
325 it.paragraph().setId(cloned_it.paragraph().id());
327 d->inset = new InsetText(this);
328 d->inset->setAutoBreakRows(true);
329 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
335 LYXERR(Debug::INFO, "Buffer::~Buffer()");
336 // here the buffer should take care that it is
337 // saved properly, before it goes into the void.
339 // GuiView already destroyed
343 // No need to do additional cleanups for internal buffer.
348 // loop over children
349 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
350 Impl::BufferPositionMap::iterator end = d->children_positions.end();
351 for (; it != end; ++it) {
352 Buffer * child = const_cast<Buffer *>(it->first);
353 // The child buffer might have been closed already.
354 if (theBufferList().isLoaded(child))
355 theBufferList().releaseChild(this, child);
359 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
360 msg += emergencyWrite();
361 Alert::warning(_("Attempting to close changed document!"), msg);
364 // clear references to children in macro tables
365 d->children_positions.clear();
366 d->position_to_children.clear();
368 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
369 Alert::warning(_("Could not remove temporary directory"),
370 bformat(_("Could not remove the temporary directory %1$s"),
371 from_utf8(d->temppath.absFilename())));
374 // Remove any previewed LaTeX snippets associated with this buffer.
375 thePreviews().removeLoader(*this);
381 Buffer * Buffer::clone() const
383 // FIXME for asynchronous export and preview: We must also clone all
384 // the child buffers!
385 return new Buffer(fileName().absFilename(), false, this);
389 bool Buffer::isClone() const
391 return d->cloned_buffer_;
395 void Buffer::changed() const
402 frontend::WorkAreaManager & Buffer::workAreaManager() const
404 LASSERT(d->wa_, /**/);
409 Text & Buffer::text() const
411 return d->inset->text();
415 Inset & Buffer::inset() const
421 BufferParams & Buffer::params()
427 BufferParams const & Buffer::params() const
433 ParagraphList & Buffer::paragraphs()
435 return text().paragraphs();
439 ParagraphList const & Buffer::paragraphs() const
441 return text().paragraphs();
445 LyXVC & Buffer::lyxvc()
451 LyXVC const & Buffer::lyxvc() const
457 string const Buffer::temppath() const
459 return d->temppath.absFilename();
463 TexRow & Buffer::texrow()
469 TexRow const & Buffer::texrow() const
475 TocBackend & Buffer::tocBackend() const
477 return d->toc_backend;
481 Undo & Buffer::undo()
487 string Buffer::latexName(bool const no_path) const
489 FileName latex_name =
490 makeLatexName(exportFileName());
491 return no_path ? latex_name.onlyFileName()
492 : latex_name.absFilename();
496 FileName Buffer::exportFileName() const
498 docstring const branch_suffix =
499 params().branchlist().getFilenameSuffix();
500 if (branch_suffix.empty())
503 string const name = fileName().onlyFileNameWithoutExt()
504 + to_utf8(branch_suffix);
505 FileName res(fileName().onlyPath().absFilename() + "/" + name);
506 res.changeExtension(fileName().extension());
512 string Buffer::logName(LogType * type) const
514 string const filename = latexName(false);
516 if (filename.empty()) {
522 string const path = temppath();
524 FileName const fname(addName(temppath(),
525 onlyFilename(changeExtension(filename,
528 // FIXME: how do we know this is the name of the build log?
529 FileName const bname(
530 addName(path, onlyFilename(
531 changeExtension(filename,
532 formats.extension(bufferFormat()) + ".out"))));
534 // Also consider the master buffer log file
535 FileName masterfname = fname;
537 if (masterBuffer() != this) {
538 string const mlogfile = masterBuffer()->logName(&mtype);
539 masterfname = FileName(mlogfile);
542 // If no Latex log or Build log is newer, show Build log
543 if (bname.exists() &&
544 ((!fname.exists() && !masterfname.exists())
545 || (fname.lastModified() < bname.lastModified()
546 && masterfname.lastModified() < bname.lastModified()))) {
547 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
550 return bname.absFilename();
551 // If we have a newer master file log or only a master log, show this
552 } else if (fname != masterfname
553 && (!fname.exists() && (masterfname.exists()
554 || fname.lastModified() < masterfname.lastModified()))) {
555 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
558 return masterfname.absFilename();
560 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
563 return fname.absFilename();
567 void Buffer::setReadonly(bool const flag)
569 if (d->read_only != flag) {
576 void Buffer::setFileName(string const & newfile)
578 d->filename = makeAbsPath(newfile);
579 setReadonly(d->filename.isReadOnly());
584 int Buffer::readHeader(Lexer & lex)
586 int unknown_tokens = 0;
588 int begin_header_line = -1;
590 // Initialize parameters that may be/go lacking in header:
591 params().branchlist().clear();
592 params().preamble.erase();
593 params().options.erase();
594 params().master.erase();
595 params().float_placement.erase();
596 params().paperwidth.erase();
597 params().paperheight.erase();
598 params().leftmargin.erase();
599 params().rightmargin.erase();
600 params().topmargin.erase();
601 params().bottommargin.erase();
602 params().headheight.erase();
603 params().headsep.erase();
604 params().footskip.erase();
605 params().columnsep.erase();
606 params().fontsCJK.erase();
607 params().listings_params.clear();
608 params().clearLayoutModules();
609 params().clearRemovedModules();
610 params().pdfoptions().clear();
611 params().indiceslist().clear();
612 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
614 for (int i = 0; i < 4; ++i) {
615 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
616 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
619 ErrorList & errorList = d->errorLists["Parse"];
628 if (token == "\\end_header")
632 if (token == "\\begin_header") {
633 begin_header_line = line;
637 LYXERR(Debug::PARSER, "Handling document header token: `"
640 string unknown = params().readToken(lex, token, d->filename.onlyPath());
641 if (!unknown.empty()) {
642 if (unknown[0] != '\\' && token == "\\textclass") {
643 Alert::warning(_("Unknown document class"),
644 bformat(_("Using the default document class, because the "
645 "class %1$s is unknown."), from_utf8(unknown)));
648 docstring const s = bformat(_("Unknown token: "
652 errorList.push_back(ErrorItem(_("Document header error"),
657 if (begin_header_line) {
658 docstring const s = _("\\begin_header is missing");
659 errorList.push_back(ErrorItem(_("Document header error"),
663 params().makeDocumentClass();
665 return unknown_tokens;
670 // changed to be public and have one parameter
671 // Returns true if "\end_document" is not read (Asger)
672 bool Buffer::readDocument(Lexer & lex)
674 ErrorList & errorList = d->errorLists["Parse"];
677 if (!lex.checkFor("\\begin_document")) {
678 docstring const s = _("\\begin_document is missing");
679 errorList.push_back(ErrorItem(_("Document header error"),
683 // we are reading in a brand new document
684 LASSERT(paragraphs().empty(), /**/);
688 if (params().outputChanges) {
689 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
690 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
691 LaTeXFeatures::isAvailable("xcolor");
693 if (!dvipost && !xcolorulem) {
694 Alert::warning(_("Changes not shown in LaTeX output"),
695 _("Changes will not be highlighted in LaTeX output, "
696 "because neither dvipost nor xcolor/ulem are installed.\n"
697 "Please install these packages or redefine "
698 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
699 } else if (!xcolorulem) {
700 Alert::warning(_("Changes not shown in LaTeX output"),
701 _("Changes will not be highlighted in LaTeX output "
702 "when using pdflatex, because xcolor and ulem are not installed.\n"
703 "Please install both packages or redefine "
704 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
708 if (!params().master.empty()) {
709 FileName const master_file = makeAbsPath(params().master,
710 onlyPath(absFileName()));
711 if (isLyXFilename(master_file.absFilename())) {
713 checkAndLoadLyXFile(master_file, true);
715 // necessary e.g. after a reload
716 // to re-register the child (bug 5873)
717 // FIXME: clean up updateMacros (here, only
718 // child registering is needed).
719 master->updateMacros();
720 // set master as master buffer, but only
721 // if we are a real child
722 if (master->isChild(this))
724 // if the master is not fully loaded
725 // it is probably just loading this
726 // child. No warning needed then.
727 else if (master->isFullyLoaded())
728 LYXERR0("The master '"
730 << "' assigned to this document ("
732 << ") does not include "
733 "this document. Ignoring the master assignment.");
738 // assure we have a default index
739 params().indiceslist().addDefault(B_("Index"));
742 bool const res = text().read(lex, errorList, d->inset);
746 updateMacroInstances();
751 bool Buffer::readString(string const & s)
753 params().compressed = false;
755 // remove dummy empty par
756 paragraphs().clear();
760 FileName const name = FileName::tempName("Buffer_readString");
761 switch (readFile(lex, name, true)) {
765 // We need to call lyx2lyx, so write the input to a file
766 ofstream os(name.toFilesystemEncoding().c_str());
769 return readFile(name);
779 bool Buffer::readFile(FileName const & filename)
781 FileName fname(filename);
783 params().compressed = fname.isZippedFile();
785 // remove dummy empty par
786 paragraphs().clear();
789 if (readFile(lex, fname) != success)
796 bool Buffer::isFullyLoaded() const
798 return d->file_fully_loaded;
802 void Buffer::setFullyLoaded(bool value)
804 d->file_fully_loaded = value;
808 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
811 LASSERT(!filename.empty(), /**/);
813 // the first (non-comment) token _must_ be...
814 if (!lex.checkFor("\\lyxformat")) {
815 Alert::error(_("Document format failure"),
816 bformat(_("%1$s is not a readable LyX document."),
817 from_utf8(filename.absFilename())));
823 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
824 // if present remove ".," from string.
825 size_t dot = tmp_format.find_first_of(".,");
826 //lyxerr << " dot found at " << dot << endl;
827 if (dot != string::npos)
828 tmp_format.erase(dot, 1);
829 int const file_format = convert<int>(tmp_format);
830 //lyxerr << "format: " << file_format << endl;
832 // save timestamp and checksum of the original disk file, making sure
833 // to not overwrite them with those of the file created in the tempdir
834 // when it has to be converted to the current format.
836 // Save the timestamp and checksum of disk file. If filename is an
837 // emergency file, save the timestamp and checksum of the original lyx file
838 // because isExternallyModified will check for this file. (BUG4193)
839 string diskfile = filename.absFilename();
840 if (suffixIs(diskfile, ".emergency"))
841 diskfile = diskfile.substr(0, diskfile.size() - 10);
842 saveCheckSum(FileName(diskfile));
845 if (file_format != LYX_FORMAT) {
848 // lyx2lyx would fail
851 FileName const tmpfile = FileName::tempName("Buffer_readFile");
852 if (tmpfile.empty()) {
853 Alert::error(_("Conversion failed"),
854 bformat(_("%1$s is from a different"
855 " version of LyX, but a temporary"
856 " file for converting it could"
858 from_utf8(filename.absFilename())));
861 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
862 if (lyx2lyx.empty()) {
863 Alert::error(_("Conversion script not found"),
864 bformat(_("%1$s is from a different"
865 " version of LyX, but the"
866 " conversion script lyx2lyx"
867 " could not be found."),
868 from_utf8(filename.absFilename())));
871 ostringstream command;
872 command << os::python()
873 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
874 << " -t " << convert<string>(LYX_FORMAT)
875 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
876 << ' ' << quoteName(filename.toFilesystemEncoding());
877 string const command_str = command.str();
879 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
881 cmd_ret const ret = runCommand(command_str);
882 if (ret.first != 0) {
883 Alert::error(_("Conversion script failed"),
884 bformat(_("%1$s is from a different version"
885 " of LyX, but the lyx2lyx script"
886 " failed to convert it."),
887 from_utf8(filename.absFilename())));
890 bool const ret = readFile(tmpfile);
891 // Do stuff with tmpfile name and buffer name here.
892 return ret ? success : failure;
897 if (readDocument(lex)) {
898 Alert::error(_("Document format failure"),
899 bformat(_("%1$s ended unexpectedly, which means"
900 " that it is probably corrupted."),
901 from_utf8(filename.absFilename())));
904 d->file_fully_loaded = true;
909 // Should probably be moved to somewhere else: BufferView? LyXView?
910 bool Buffer::save() const
912 // We don't need autosaves in the immediate future. (Asger)
913 resetAutosaveTimers();
915 string const encodedFilename = d->filename.toFilesystemEncoding();
918 bool madeBackup = false;
920 // make a backup if the file already exists
921 if (lyxrc.make_backup && fileName().exists()) {
922 backupName = FileName(absFileName() + '~');
923 if (!lyxrc.backupdir_path.empty()) {
924 string const mangledName =
925 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
926 backupName = FileName(addName(lyxrc.backupdir_path,
929 if (fileName().copyTo(backupName)) {
932 Alert::error(_("Backup failure"),
933 bformat(_("Cannot create backup file %1$s.\n"
934 "Please check whether the directory exists and is writeable."),
935 from_utf8(backupName.absFilename())));
936 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
940 // ask if the disk file has been externally modified (use checksum method)
941 if (fileName().exists() && isExternallyModified(checksum_method)) {
942 docstring const file = makeDisplayPath(absFileName(), 20);
943 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
944 "you want to overwrite this file?"), file);
945 int const ret = Alert::prompt(_("Overwrite modified file?"),
946 text, 1, 1, _("&Overwrite"), _("&Cancel"));
951 if (writeFile(d->filename)) {
955 // Saving failed, so backup is not backup
957 backupName.moveTo(d->filename);
963 bool Buffer::writeFile(FileName const & fname) const
965 if (d->read_only && fname == d->filename)
970 docstring const str = bformat(_("Saving document %1$s..."),
971 makeDisplayPath(fname.absFilename()));
974 if (params().compressed) {
975 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
976 retval = ofs && write(ofs);
978 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
979 retval = ofs && write(ofs);
983 message(str + _(" could not write file!"));
987 removeAutosaveFile();
989 saveCheckSum(d->filename);
990 message(str + _(" done."));
996 docstring Buffer::emergencyWrite()
998 // No need to save if the buffer has not changed.
1002 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1004 docstring user_message = bformat(
1005 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1007 // We try to save three places:
1008 // 1) Same place as document. Unless it is an unnamed doc.
1010 string s = absFileName();
1013 if (writeFile(FileName(s))) {
1015 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1016 return user_message;
1018 user_message += _(" Save failed! Trying again...\n");
1022 // 2) In HOME directory.
1023 string s = addName(package().home_dir().absFilename(), absFileName());
1025 lyxerr << ' ' << s << endl;
1026 if (writeFile(FileName(s))) {
1028 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1029 return user_message;
1032 user_message += _(" Save failed! Trying yet again...\n");
1034 // 3) In "/tmp" directory.
1035 // MakeAbsPath to prepend the current
1036 // drive letter on OS/2
1037 s = addName(package().temp_dir().absFilename(), absFileName());
1039 lyxerr << ' ' << s << endl;
1040 if (writeFile(FileName(s))) {
1042 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1043 return user_message;
1046 user_message += _(" Save failed! Bummer. Document is lost.");
1049 return user_message;
1053 bool Buffer::write(ostream & ofs) const
1056 // Use the standard "C" locale for file output.
1057 ofs.imbue(locale::classic());
1060 // The top of the file should not be written by params().
1062 // write out a comment in the top of the file
1063 ofs << "#LyX " << lyx_version
1064 << " created this file. For more info see http://www.lyx.org/\n"
1065 << "\\lyxformat " << LYX_FORMAT << "\n"
1066 << "\\begin_document\n";
1068 /// For each author, set 'used' to true if there is a change
1069 /// by this author in the document; otherwise set it to 'false'.
1070 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1071 AuthorList::Authors::const_iterator a_end = params().authors().end();
1072 for (; a_it != a_end; ++a_it)
1073 a_it->setUsed(false);
1075 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1076 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1077 for ( ; it != end; ++it)
1078 it->checkAuthors(params().authors());
1080 // now write out the buffer parameters.
1081 ofs << "\\begin_header\n";
1082 params().writeFile(ofs);
1083 ofs << "\\end_header\n";
1086 ofs << "\n\\begin_body\n";
1088 ofs << "\n\\end_body\n";
1090 // Write marker that shows file is complete
1091 ofs << "\\end_document" << endl;
1093 // Shouldn't really be needed....
1096 // how to check if close went ok?
1097 // Following is an attempt... (BE 20001011)
1099 // good() returns false if any error occured, including some
1100 // formatting error.
1101 // bad() returns true if something bad happened in the buffer,
1102 // which should include file system full errors.
1107 lyxerr << "File was not closed properly." << endl;
1114 bool Buffer::makeLaTeXFile(FileName const & fname,
1115 string const & original_path,
1116 OutputParams const & runparams_in,
1117 bool output_preamble, bool output_body) const
1119 OutputParams runparams = runparams_in;
1120 if (params().useXetex)
1121 runparams.flavor = OutputParams::XETEX;
1123 string const encoding = runparams.encoding->iconvName();
1124 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1127 try { ofs.reset(encoding); }
1128 catch (iconv_codecvt_facet_exception & e) {
1129 lyxerr << "Caught iconv exception: " << e.what() << endl;
1130 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1131 "verify that the support software for your encoding (%1$s) is "
1132 "properly installed"), from_ascii(encoding)));
1135 if (!openFileWrite(ofs, fname))
1138 //TexStream ts(ofs.rdbuf(), &texrow());
1139 ErrorList & errorList = d->errorLists["Export"];
1141 bool failed_export = false;
1144 writeLaTeXSource(ofs, original_path,
1145 runparams, output_preamble, output_body);
1147 catch (EncodingException & e) {
1148 odocstringstream ods;
1149 ods.put(e.failed_char);
1151 oss << "0x" << hex << e.failed_char << dec;
1152 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1153 " (code point %2$s)"),
1154 ods.str(), from_utf8(oss.str()));
1155 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1156 "representable in the chosen encoding.\n"
1157 "Changing the document encoding to utf8 could help."),
1158 e.par_id, e.pos, e.pos + 1));
1159 failed_export = true;
1161 catch (iconv_codecvt_facet_exception & e) {
1162 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1163 _(e.what()), -1, 0, 0));
1164 failed_export = true;
1166 catch (exception const & e) {
1167 errorList.push_back(ErrorItem(_("conversion failed"),
1168 _(e.what()), -1, 0, 0));
1169 failed_export = true;
1172 lyxerr << "Caught some really weird exception..." << endl;
1178 failed_export = true;
1179 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1183 return !failed_export;
1187 void Buffer::writeLaTeXSource(odocstream & os,
1188 string const & original_path,
1189 OutputParams const & runparams_in,
1190 bool const output_preamble, bool const output_body) const
1192 // The child documents, if any, shall be already loaded at this point.
1194 OutputParams runparams = runparams_in;
1196 // Classify the unicode characters appearing in math insets
1197 Encodings::initUnicodeMath(*this);
1199 // validate the buffer.
1200 LYXERR(Debug::LATEX, " Validating buffer...");
1201 LaTeXFeatures features(*this, params(), runparams);
1203 LYXERR(Debug::LATEX, " Buffer validation done.");
1205 // The starting paragraph of the coming rows is the
1206 // first paragraph of the document. (Asger)
1207 if (output_preamble && runparams.nice) {
1208 os << "%% LyX " << lyx_version << " created this file. "
1209 "For more info, see http://www.lyx.org/.\n"
1210 "%% Do not edit unless you really know what "
1212 d->texrow.newline();
1213 d->texrow.newline();
1215 LYXERR(Debug::INFO, "lyx document header finished");
1217 // Don't move this behind the parent_buffer=0 code below,
1218 // because then the macros will not get the right "redefinition"
1219 // flag as they don't see the parent macros which are output before.
1222 // fold macros if possible, still with parent buffer as the
1223 // macros will be put in the prefix anyway.
1224 updateMacroInstances();
1226 // There are a few differences between nice LaTeX and usual files:
1227 // usual is \batchmode and has a
1228 // special input@path to allow the including of figures
1229 // with either \input or \includegraphics (what figinsets do).
1230 // input@path is set when the actual parameter
1231 // original_path is set. This is done for usual tex-file, but not
1232 // for nice-latex-file. (Matthias 250696)
1233 // Note that input@path is only needed for something the user does
1234 // in the preamble, included .tex files or ERT, files included by
1235 // LyX work without it.
1236 if (output_preamble) {
1237 if (!runparams.nice) {
1238 // code for usual, NOT nice-latex-file
1239 os << "\\batchmode\n"; // changed
1240 // from \nonstopmode
1241 d->texrow.newline();
1243 if (!original_path.empty()) {
1245 // We don't know the encoding of inputpath
1246 docstring const inputpath = from_utf8(latex_path(original_path));
1247 os << "\\makeatletter\n"
1248 << "\\def\\input@path{{"
1249 << inputpath << "/}}\n"
1250 << "\\makeatother\n";
1251 d->texrow.newline();
1252 d->texrow.newline();
1253 d->texrow.newline();
1256 // get parent macros (if this buffer has a parent) which will be
1257 // written at the document begin further down.
1258 MacroSet parentMacros;
1259 listParentMacros(parentMacros, features);
1261 // Write the preamble
1262 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1264 runparams.use_japanese = features.isRequired("japanese");
1270 os << "\\begin{document}\n";
1271 d->texrow.newline();
1273 // output the parent macros
1274 MacroSet::iterator it = parentMacros.begin();
1275 MacroSet::iterator end = parentMacros.end();
1276 for (; it != end; ++it)
1277 (*it)->write(os, true);
1278 } // output_preamble
1280 d->texrow.start(paragraphs().begin()->id(), 0);
1282 LYXERR(Debug::INFO, "preamble finished, now the body.");
1284 // if we are doing a real file with body, even if this is the
1285 // child of some other buffer, let's cut the link here.
1286 // This happens for example if only a child document is printed.
1287 Buffer const * save_parent = 0;
1288 if (output_preamble) {
1289 save_parent = d->parent();
1294 latexParagraphs(*this, text(), os, d->texrow, runparams);
1296 // Restore the parenthood if needed
1297 if (output_preamble)
1298 d->setParent(save_parent);
1300 // add this just in case after all the paragraphs
1302 d->texrow.newline();
1304 if (output_preamble) {
1305 os << "\\end{document}\n";
1306 d->texrow.newline();
1307 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1309 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1311 runparams_in.encoding = runparams.encoding;
1313 // Just to be sure. (Asger)
1314 d->texrow.newline();
1316 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1317 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1321 bool Buffer::isLatex() const
1323 return params().documentClass().outputType() == LATEX;
1327 bool Buffer::isLiterate() const
1329 return params().documentClass().outputType() == LITERATE;
1333 bool Buffer::isDocBook() const
1335 return params().documentClass().outputType() == DOCBOOK;
1339 void Buffer::makeDocBookFile(FileName const & fname,
1340 OutputParams const & runparams,
1341 bool const body_only) const
1343 LYXERR(Debug::LATEX, "makeDocBookFile...");
1346 if (!openFileWrite(ofs, fname))
1349 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1353 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1357 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1358 OutputParams const & runparams,
1359 bool const only_body) const
1361 LaTeXFeatures features(*this, params(), runparams);
1366 DocumentClass const & tclass = params().documentClass();
1367 string const top_element = tclass.latexname();
1370 if (runparams.flavor == OutputParams::XML)
1371 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1374 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1377 if (! tclass.class_header().empty())
1378 os << from_ascii(tclass.class_header());
1379 else if (runparams.flavor == OutputParams::XML)
1380 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1381 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1383 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1385 docstring preamble = from_utf8(params().preamble);
1386 if (runparams.flavor != OutputParams::XML ) {
1387 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1388 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1389 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1390 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1393 string const name = runparams.nice
1394 ? changeExtension(absFileName(), ".sgml") : fname;
1395 preamble += features.getIncludedFiles(name);
1396 preamble += features.getLyXSGMLEntities();
1398 if (!preamble.empty()) {
1399 os << "\n [ " << preamble << " ]";
1404 string top = top_element;
1406 if (runparams.flavor == OutputParams::XML)
1407 top += params().language->code();
1409 top += params().language->code().substr(0, 2);
1412 if (!params().options.empty()) {
1414 top += params().options;
1417 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1418 << " file was created by LyX " << lyx_version
1419 << "\n See http://www.lyx.org/ for more information -->\n";
1421 params().documentClass().counters().reset();
1425 sgml::openTag(os, top);
1427 docbookParagraphs(text(), *this, os, runparams);
1428 sgml::closeTag(os, top_element);
1432 void Buffer::makeLyXHTMLFile(FileName const & fname,
1433 OutputParams const & runparams,
1434 bool const body_only) const
1436 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1439 if (!openFileWrite(ofs, fname))
1442 writeLyXHTMLSource(ofs, runparams, body_only);
1446 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1450 void Buffer::writeLyXHTMLSource(odocstream & os,
1451 OutputParams const & runparams,
1452 bool const only_body) const
1454 LaTeXFeatures features(*this, params(), runparams);
1456 updateLabels(UpdateMaster, true);
1461 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1462 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";
1463 // FIXME Language should be set properly.
1464 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1467 // FIXME Presumably need to set this right
1468 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1469 // FIXME Get this during validation? What about other meta-data?
1470 os << "<title>TBA</title>\n";
1472 os << "\n<!-- Text Class Preamble -->\n"
1473 << features.getTClassHTMLPreamble()
1474 << "\n<!-- Premable Snippets -->\n"
1475 << from_utf8(features.getPreambleSnippets());
1477 os << "\n<!-- Layout-provided Styles -->\n";
1478 docstring const styleinfo = features.getTClassHTMLStyles();
1479 if (!styleinfo.empty()) {
1480 os << "<style type='text/css'>\n"
1484 os << "</head>\n<body>\n";
1488 params().documentClass().counters().reset();
1489 xhtmlParagraphs(text(), *this, xs, runparams);
1491 os << "</body>\n</html>\n";
1495 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1496 // Other flags: -wall -v0 -x
1497 int Buffer::runChktex()
1501 // get LaTeX-Filename
1502 FileName const path(temppath());
1503 string const name = addName(path.absFilename(), latexName());
1504 string const org_path = filePath();
1506 PathChanger p(path); // path to LaTeX file
1507 message(_("Running chktex..."));
1509 // Generate the LaTeX file if neccessary
1510 OutputParams runparams(¶ms().encoding());
1511 runparams.flavor = OutputParams::LATEX;
1512 runparams.nice = false;
1513 makeLaTeXFile(FileName(name), org_path, runparams);
1516 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1517 int const res = chktex.run(terr); // run chktex
1520 Alert::error(_("chktex failure"),
1521 _("Could not run chktex successfully."));
1522 } else if (res > 0) {
1523 ErrorList & errlist = d->errorLists["ChkTeX"];
1525 bufferErrors(terr, errlist);
1536 void Buffer::validate(LaTeXFeatures & features) const
1538 params().validate(features);
1542 for_each(paragraphs().begin(), paragraphs().end(),
1543 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1545 if (lyxerr.debugging(Debug::LATEX)) {
1546 features.showStruct();
1551 void Buffer::getLabelList(vector<docstring> & list) const
1553 // If this is a child document, use the parent's list instead.
1554 Buffer const * const pbuf = d->parent();
1556 pbuf->getLabelList(list);
1561 Toc & toc = d->toc_backend.toc("label");
1562 TocIterator toc_it = toc.begin();
1563 TocIterator end = toc.end();
1564 for (; toc_it != end; ++toc_it) {
1565 if (toc_it->depth() == 0)
1566 list.push_back(toc_it->str());
1571 void Buffer::updateBibfilesCache(UpdateScope scope) const
1573 // If this is a child document, use the parent's cache instead.
1574 Buffer const * const pbuf = d->parent();
1575 if (pbuf && scope != UpdateChildOnly) {
1576 pbuf->updateBibfilesCache();
1580 d->bibfilesCache_.clear();
1581 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1582 if (it->lyxCode() == BIBTEX_CODE) {
1583 InsetBibtex const & inset =
1584 static_cast<InsetBibtex const &>(*it);
1585 support::FileNameList const bibfiles = inset.getBibFiles();
1586 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1589 } else if (it->lyxCode() == INCLUDE_CODE) {
1590 InsetInclude & inset =
1591 static_cast<InsetInclude &>(*it);
1592 inset.updateBibfilesCache();
1593 support::FileNameList const & bibfiles =
1594 inset.getBibfilesCache();
1595 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1600 // the bibinfo cache is now invalid
1601 d->bibinfoCacheValid_ = false;
1605 void Buffer::invalidateBibinfoCache()
1607 d->bibinfoCacheValid_ = false;
1611 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1613 // If this is a child document, use the parent's cache instead.
1614 Buffer const * const pbuf = d->parent();
1615 if (pbuf && scope != UpdateChildOnly)
1616 return pbuf->getBibfilesCache();
1618 // We update the cache when first used instead of at loading time.
1619 if (d->bibfilesCache_.empty())
1620 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1622 return d->bibfilesCache_;
1626 BiblioInfo const & Buffer::masterBibInfo() const
1628 // if this is a child document and the parent is already loaded
1629 // use the parent's list instead [ale990412]
1630 Buffer const * const tmp = masterBuffer();
1633 return tmp->masterBibInfo();
1634 return localBibInfo();
1638 BiblioInfo const & Buffer::localBibInfo() const
1640 if (d->bibinfoCacheValid_) {
1641 support::FileNameList const & bibfilesCache = getBibfilesCache();
1642 // compare the cached timestamps with the actual ones.
1643 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1644 support::FileNameList::const_iterator en = bibfilesCache.end();
1645 for (; ei != en; ++ ei) {
1646 time_t lastw = ei->lastModified();
1647 if (lastw != d->bibfileStatus_[*ei]) {
1648 d->bibinfoCacheValid_ = false;
1649 d->bibfileStatus_[*ei] = lastw;
1655 if (!d->bibinfoCacheValid_) {
1656 d->bibinfo_.clear();
1657 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1658 it->fillWithBibKeys(d->bibinfo_, it);
1659 d->bibinfoCacheValid_ = true;
1665 bool Buffer::isDepClean(string const & name) const
1667 DepClean::const_iterator const it = d->dep_clean.find(name);
1668 if (it == d->dep_clean.end())
1674 void Buffer::markDepClean(string const & name)
1676 d->dep_clean[name] = true;
1680 bool Buffer::isExportableFormat(string const & format) const
1682 typedef vector<Format const *> Formats;
1684 formats = exportableFormats(true);
1685 Formats::const_iterator fit = formats.begin();
1686 Formats::const_iterator end = formats.end();
1687 for (; fit != end ; ++fit) {
1688 if ((*fit)->name() == format)
1695 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1698 // FIXME? if there is an Buffer LFUN that can be dispatched even
1699 // if internal, put a switch '(cmd.action)' here.
1705 switch (cmd.action) {
1707 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1708 flag.setOnOff(isReadonly());
1711 // FIXME: There is need for a command-line import.
1712 //case LFUN_BUFFER_IMPORT:
1714 case LFUN_BUFFER_AUTO_SAVE:
1717 case LFUN_BUFFER_EXPORT_CUSTOM:
1718 // FIXME: Nothing to check here?
1721 case LFUN_BUFFER_EXPORT: {
1722 docstring const arg = cmd.argument();
1723 enable = arg == "custom" || isExportable(to_utf8(arg));
1725 flag.message(bformat(
1726 _("Don't know how to export to format: %1$s"), arg));
1730 case LFUN_BUFFER_CHKTEX:
1731 enable = isLatex() && !lyxrc.chktex_command.empty();
1734 case LFUN_BUILD_PROGRAM:
1735 enable = isExportable("program");
1738 case LFUN_BRANCH_ACTIVATE:
1739 case LFUN_BRANCH_DEACTIVATE: {
1740 BranchList const & branchList = params().branchlist();
1741 docstring const branchName = cmd.argument();
1742 enable = !branchName.empty() && branchList.find(branchName);
1746 case LFUN_BRANCH_ADD:
1747 case LFUN_BRANCHES_RENAME:
1748 case LFUN_BUFFER_PRINT:
1749 // if no Buffer is present, then of course we won't be called!
1752 case LFUN_BUFFER_LANGUAGE:
1753 enable = !isReadonly();
1759 flag.setEnabled(enable);
1764 void Buffer::dispatch(string const & command, DispatchResult & result)
1766 return dispatch(lyxaction.lookupFunc(command), result);
1770 // NOTE We can end up here even if we have no GUI, because we are called
1771 // by LyX::exec to handled command-line requests. So we may need to check
1772 // whether we have a GUI or not. The boolean use_gui holds this information.
1773 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1776 // FIXME? if there is an Buffer LFUN that can be dispatched even
1777 // if internal, put a switch '(cmd.action)' here.
1778 dr.dispatched(false);
1781 string const argument = to_utf8(func.argument());
1782 // We'll set this back to false if need be.
1783 bool dispatched = true;
1784 undo().beginUndoGroup();
1786 switch (func.action) {
1787 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1788 if (lyxvc().inUse())
1789 lyxvc().toggleReadOnly();
1791 setReadonly(!isReadonly());
1794 case LFUN_BUFFER_EXPORT: {
1795 bool success = doExport(argument, false);
1796 dr.setError(success);
1798 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1803 case LFUN_BUILD_PROGRAM:
1804 doExport("program", true);
1807 case LFUN_BUFFER_CHKTEX:
1811 case LFUN_BUFFER_EXPORT_CUSTOM: {
1813 string command = split(argument, format_name, ' ');
1814 Format const * format = formats.getFormat(format_name);
1816 lyxerr << "Format \"" << format_name
1817 << "\" not recognized!"
1822 // The name of the file created by the conversion process
1825 // Output to filename
1826 if (format->name() == "lyx") {
1827 string const latexname = latexName(false);
1828 filename = changeExtension(latexname,
1829 format->extension());
1830 filename = addName(temppath(), filename);
1832 if (!writeFile(FileName(filename)))
1836 doExport(format_name, true, filename);
1839 // Substitute $$FName for filename
1840 if (!contains(command, "$$FName"))
1841 command = "( " + command + " ) < $$FName";
1842 command = subst(command, "$$FName", filename);
1844 // Execute the command in the background
1846 call.startscript(Systemcall::DontWait, command);
1850 // FIXME: There is need for a command-line import.
1852 case LFUN_BUFFER_IMPORT:
1857 case LFUN_BUFFER_AUTO_SAVE:
1861 case LFUN_BRANCH_ADD: {
1862 docstring const branch_name = func.argument();
1863 if (branch_name.empty()) {
1867 BranchList & branch_list = params().branchlist();
1868 Branch * branch = branch_list.find(branch_name);
1870 LYXERR0("Branch " << branch_name << " already exists.");
1872 docstring const msg =
1873 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1876 branch_list.add(branch_name);
1877 branch = branch_list.find(branch_name);
1878 string const x11hexname = X11hexname(branch->color());
1879 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1880 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1882 dr.update(Update::Force);
1887 case LFUN_BRANCH_ACTIVATE:
1888 case LFUN_BRANCH_DEACTIVATE: {
1889 BranchList & branchList = params().branchlist();
1890 docstring const branchName = func.argument();
1891 // the case without a branch name is handled elsewhere
1892 if (branchName.empty()) {
1896 Branch * branch = branchList.find(branchName);
1898 LYXERR0("Branch " << branchName << " does not exist.");
1900 docstring const msg =
1901 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1904 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1906 dr.update(Update::Force);
1911 case LFUN_BRANCHES_RENAME: {
1912 if (func.argument().empty())
1915 docstring const oldname = from_utf8(func.getArg(0));
1916 docstring const newname = from_utf8(func.getArg(1));
1917 InsetIterator it = inset_iterator_begin(inset());
1918 InsetIterator const end = inset_iterator_end(inset());
1919 bool success = false;
1920 for (; it != end; ++it) {
1921 if (it->lyxCode() == BRANCH_CODE) {
1922 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1923 if (ins.branch() == oldname) {
1924 undo().recordUndo(it);
1925 ins.rename(newname);
1930 if (it->lyxCode() == INCLUDE_CODE) {
1931 // get buffer of external file
1932 InsetInclude const & ins =
1933 static_cast<InsetInclude const &>(*it);
1934 Buffer * child = ins.getChildBuffer();
1937 child->dispatch(func, dr);
1942 dr.update(Update::Force);
1946 case LFUN_BUFFER_PRINT: {
1947 // we'll assume there's a problem until we succeed
1949 string target = func.getArg(0);
1950 string target_name = func.getArg(1);
1951 string command = func.getArg(2);
1954 || target_name.empty()
1955 || command.empty()) {
1956 LYXERR0("Unable to parse " << func.argument());
1957 docstring const msg =
1958 bformat(_("Unable to parse \"%1$s\""), func.argument());
1962 if (target != "printer" && target != "file") {
1963 LYXERR0("Unrecognized target \"" << target << '"');
1964 docstring const msg =
1965 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1970 if (!doExport("dvi", true)) {
1971 showPrintError(absFileName());
1972 dr.setMessage(_("Error exporting to DVI."));
1976 // Push directory path.
1977 string const path = temppath();
1978 // Prevent the compiler from optimizing away p
1982 // there are three cases here:
1983 // 1. we print to a file
1984 // 2. we print directly to a printer
1985 // 3. we print using a spool command (print to file first)
1988 string const dviname = changeExtension(latexName(true), "dvi");
1990 if (target == "printer") {
1991 if (!lyxrc.print_spool_command.empty()) {
1992 // case 3: print using a spool
1993 string const psname = changeExtension(dviname,".ps");
1994 command += ' ' + lyxrc.print_to_file
1997 + quoteName(dviname);
1999 string command2 = lyxrc.print_spool_command + ' ';
2000 if (target_name != "default") {
2001 command2 += lyxrc.print_spool_printerprefix
2005 command2 += quoteName(psname);
2007 // If successful, then spool command
2008 res = one.startscript(Systemcall::Wait, command);
2011 // If there's no GUI, we have to wait on this command. Otherwise,
2012 // LyX deletes the temporary directory, and with it the spooled
2013 // file, before it can be printed!!
2014 Systemcall::Starttype stype = use_gui ?
2015 Systemcall::DontWait : Systemcall::Wait;
2016 res = one.startscript(stype, command2);
2019 // case 2: print directly to a printer
2020 if (target_name != "default")
2021 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2023 Systemcall::Starttype stype = use_gui ?
2024 Systemcall::DontWait : Systemcall::Wait;
2025 res = one.startscript(stype, command + quoteName(dviname));
2029 // case 1: print to a file
2030 FileName const filename(makeAbsPath(target_name, filePath()));
2031 FileName const dvifile(makeAbsPath(dviname, path));
2032 if (filename.exists()) {
2033 docstring text = bformat(
2034 _("The file %1$s already exists.\n\n"
2035 "Do you want to overwrite that file?"),
2036 makeDisplayPath(filename.absFilename()));
2037 if (Alert::prompt(_("Overwrite file?"),
2038 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2041 command += ' ' + lyxrc.print_to_file
2042 + quoteName(filename.toFilesystemEncoding())
2044 + quoteName(dvifile.toFilesystemEncoding());
2046 Systemcall::Starttype stype = use_gui ?
2047 Systemcall::DontWait : Systemcall::Wait;
2048 res = one.startscript(stype, command);
2054 dr.setMessage(_("Error running external commands."));
2055 showPrintError(absFileName());
2060 case LFUN_BUFFER_LANGUAGE: {
2061 Language const * oldL = params().language;
2062 Language const * newL = languages.getLanguage(argument);
2063 if (!newL || oldL == newL)
2065 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2066 changeLanguage(oldL, newL);
2074 dr.dispatched(dispatched);
2075 undo().endUndoGroup();
2079 void Buffer::changeLanguage(Language const * from, Language const * to)
2081 LASSERT(from, /**/);
2084 for_each(par_iterator_begin(),
2086 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2090 bool Buffer::isMultiLingual() const
2092 ParConstIterator end = par_iterator_end();
2093 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2094 if (it->isMultiLingual(params()))
2101 DocIterator Buffer::getParFromID(int const id) const
2103 Buffer * buf = const_cast<Buffer *>(this);
2105 // John says this is called with id == -1 from undo
2106 lyxerr << "getParFromID(), id: " << id << endl;
2107 return doc_iterator_end(buf);
2110 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2111 if (it.paragraph().id() == id)
2114 return doc_iterator_end(buf);
2118 bool Buffer::hasParWithID(int const id) const
2120 return !getParFromID(id).atEnd();
2124 ParIterator Buffer::par_iterator_begin()
2126 return ParIterator(doc_iterator_begin(this));
2130 ParIterator Buffer::par_iterator_end()
2132 return ParIterator(doc_iterator_end(this));
2136 ParConstIterator Buffer::par_iterator_begin() const
2138 return ParConstIterator(doc_iterator_begin(this));
2142 ParConstIterator Buffer::par_iterator_end() const
2144 return ParConstIterator(doc_iterator_end(this));
2148 Language const * Buffer::language() const
2150 return params().language;
2154 docstring const Buffer::B_(string const & l10n) const
2156 return params().B_(l10n);
2160 bool Buffer::isClean() const
2162 return d->lyx_clean;
2166 bool Buffer::isBakClean() const
2168 return d->bak_clean;
2172 bool Buffer::isExternallyModified(CheckMethod method) const
2174 LASSERT(d->filename.exists(), /**/);
2175 // if method == timestamp, check timestamp before checksum
2176 return (method == checksum_method
2177 || d->timestamp_ != d->filename.lastModified())
2178 && d->checksum_ != d->filename.checksum();
2182 void Buffer::saveCheckSum(FileName const & file) const
2184 if (file.exists()) {
2185 d->timestamp_ = file.lastModified();
2186 d->checksum_ = file.checksum();
2188 // in the case of save to a new file.
2195 void Buffer::markClean() const
2197 if (!d->lyx_clean) {
2198 d->lyx_clean = true;
2201 // if the .lyx file has been saved, we don't need an
2203 d->bak_clean = true;
2207 void Buffer::markBakClean() const
2209 d->bak_clean = true;
2213 void Buffer::setUnnamed(bool flag)
2219 bool Buffer::isUnnamed() const
2226 /// Don't check unnamed, here: isInternal() is used in
2227 /// newBuffer(), where the unnamed flag has not been set by anyone
2228 /// yet. Also, for an internal buffer, there should be no need for
2229 /// retrieving fileName() nor for checking if it is unnamed or not.
2230 bool Buffer::isInternal() const
2232 return fileName().extension() == "internal";
2236 void Buffer::markDirty()
2239 d->lyx_clean = false;
2242 d->bak_clean = false;
2244 DepClean::iterator it = d->dep_clean.begin();
2245 DepClean::const_iterator const end = d->dep_clean.end();
2247 for (; it != end; ++it)
2252 FileName Buffer::fileName() const
2258 string Buffer::absFileName() const
2260 return d->filename.absFilename();
2264 string Buffer::filePath() const
2266 return d->filename.onlyPath().absFilename() + "/";
2270 bool Buffer::isReadonly() const
2272 return d->read_only;
2276 void Buffer::setParent(Buffer const * buffer)
2278 // Avoids recursive include.
2279 d->setParent(buffer == this ? 0 : buffer);
2284 Buffer const * Buffer::parent() const
2290 void Buffer::collectRelatives(BufferSet & bufs) const
2294 parent()->collectRelatives(bufs);
2296 // loop over children
2297 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2298 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2299 for (; it != end; ++it)
2300 bufs.insert(const_cast<Buffer *>(it->first));
2304 std::vector<Buffer const *> Buffer::allRelatives() const
2307 collectRelatives(bufs);
2308 BufferSet::iterator it = bufs.begin();
2309 std::vector<Buffer const *> ret;
2310 for (; it != bufs.end(); ++it)
2316 Buffer const * Buffer::masterBuffer() const
2318 Buffer const * const pbuf = d->parent();
2322 return pbuf->masterBuffer();
2326 bool Buffer::isChild(Buffer * child) const
2328 return d->children_positions.find(child) != d->children_positions.end();
2332 DocIterator Buffer::firstChildPosition(Buffer const * child)
2334 Impl::BufferPositionMap::iterator it;
2335 it = d->children_positions.find(child);
2336 if (it == d->children_positions.end())
2337 return DocIterator(this);
2342 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2344 // loop over children
2345 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2346 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2347 for (; it != end; ++it) {
2348 Buffer * child = const_cast<Buffer *>(it->first);
2349 clist.push_back(child);
2350 if (grand_children) {
2351 // there might be grandchildren
2352 std::vector<Buffer *> glist = child->getChildren();
2353 for (vector<Buffer *>::const_iterator git = glist.begin();
2354 git != glist.end(); ++git)
2355 clist.push_back(*git);
2361 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2363 std::vector<Buffer *> v;
2364 getChildren(v, grand_children);
2369 template<typename M>
2370 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2375 typename M::iterator it = m.lower_bound(x);
2376 if (it == m.begin())
2384 MacroData const * Buffer::getBufferMacro(docstring const & name,
2385 DocIterator const & pos) const
2387 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2389 // if paragraphs have no macro context set, pos will be empty
2393 // we haven't found anything yet
2394 DocIterator bestPos = par_iterator_begin();
2395 MacroData const * bestData = 0;
2397 // find macro definitions for name
2398 Impl::NamePositionScopeMacroMap::iterator nameIt
2399 = d->macros.find(name);
2400 if (nameIt != d->macros.end()) {
2401 // find last definition in front of pos or at pos itself
2402 Impl::PositionScopeMacroMap::const_iterator it
2403 = greatest_below(nameIt->second, pos);
2404 if (it != nameIt->second.end()) {
2406 // scope ends behind pos?
2407 if (pos < it->second.first) {
2408 // Looks good, remember this. If there
2409 // is no external macro behind this,
2410 // we found the right one already.
2411 bestPos = it->first;
2412 bestData = &it->second.second;
2416 // try previous macro if there is one
2417 if (it == nameIt->second.begin())
2424 // find macros in included files
2425 Impl::PositionScopeBufferMap::const_iterator it
2426 = greatest_below(d->position_to_children, pos);
2427 if (it == d->position_to_children.end())
2428 // no children before
2432 // do we know something better (i.e. later) already?
2433 if (it->first < bestPos )
2436 // scope ends behind pos?
2437 if (pos < it->second.first) {
2438 // look for macro in external file
2439 d->macro_lock = true;
2440 MacroData const * data
2441 = it->second.second->getMacro(name, false);
2442 d->macro_lock = false;
2444 bestPos = it->first;
2450 // try previous file if there is one
2451 if (it == d->position_to_children.begin())
2456 // return the best macro we have found
2461 MacroData const * Buffer::getMacro(docstring const & name,
2462 DocIterator const & pos, bool global) const
2467 // query buffer macros
2468 MacroData const * data = getBufferMacro(name, pos);
2472 // If there is a master buffer, query that
2473 Buffer const * const pbuf = d->parent();
2475 d->macro_lock = true;
2476 MacroData const * macro = pbuf->getMacro(
2477 name, *this, false);
2478 d->macro_lock = false;
2484 data = MacroTable::globalMacros().get(name);
2493 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2495 // set scope end behind the last paragraph
2496 DocIterator scope = par_iterator_begin();
2497 scope.pit() = scope.lastpit() + 1;
2499 return getMacro(name, scope, global);
2503 MacroData const * Buffer::getMacro(docstring const & name,
2504 Buffer const & child, bool global) const
2506 // look where the child buffer is included first
2507 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2508 if (it == d->children_positions.end())
2511 // check for macros at the inclusion position
2512 return getMacro(name, it->second, global);
2516 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2518 pit_type lastpit = it.lastpit();
2520 // look for macros in each paragraph
2521 while (it.pit() <= lastpit) {
2522 Paragraph & par = it.paragraph();
2524 // iterate over the insets of the current paragraph
2525 InsetList const & insets = par.insetList();
2526 InsetList::const_iterator iit = insets.begin();
2527 InsetList::const_iterator end = insets.end();
2528 for (; iit != end; ++iit) {
2529 it.pos() = iit->pos;
2531 // is it a nested text inset?
2532 if (iit->inset->asInsetText()) {
2533 // Inset needs its own scope?
2534 InsetText const * itext = iit->inset->asInsetText();
2535 bool newScope = itext->isMacroScope();
2537 // scope which ends just behind the inset
2538 DocIterator insetScope = it;
2541 // collect macros in inset
2542 it.push_back(CursorSlice(*iit->inset));
2543 updateMacros(it, newScope ? insetScope : scope);
2548 // is it an external file?
2549 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2550 // get buffer of external file
2551 InsetInclude const & inset =
2552 static_cast<InsetInclude const &>(*iit->inset);
2553 d->macro_lock = true;
2554 Buffer * child = inset.getChildBuffer();
2555 d->macro_lock = false;
2559 // register its position, but only when it is
2560 // included first in the buffer
2561 if (d->children_positions.find(child) ==
2562 d->children_positions.end())
2563 d->children_positions[child] = it;
2565 // register child with its scope
2566 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2570 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2574 MathMacroTemplate & macroTemplate =
2575 static_cast<MathMacroTemplate &>(*iit->inset);
2576 MacroContext mc(this, it);
2577 macroTemplate.updateToContext(mc);
2580 bool valid = macroTemplate.validMacro();
2581 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2582 // then the BufferView's cursor will be invalid in
2583 // some cases which leads to crashes.
2588 // FIXME (Abdel), I don't understandt why we pass 'it' here
2589 // instead of 'macroTemplate' defined above... is this correct?
2590 d->macros[macroTemplate.name()][it] =
2591 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2601 void Buffer::updateMacros() const
2606 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2608 // start with empty table
2610 d->children_positions.clear();
2611 d->position_to_children.clear();
2613 // Iterate over buffer, starting with first paragraph
2614 // The scope must be bigger than any lookup DocIterator
2615 // later. For the global lookup, lastpit+1 is used, hence
2616 // we use lastpit+2 here.
2617 DocIterator it = par_iterator_begin();
2618 DocIterator outerScope = it;
2619 outerScope.pit() = outerScope.lastpit() + 2;
2620 updateMacros(it, outerScope);
2624 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2626 InsetIterator it = inset_iterator_begin(inset());
2627 InsetIterator const end = inset_iterator_end(inset());
2628 for (; it != end; ++it) {
2629 if (it->lyxCode() == BRANCH_CODE) {
2630 InsetBranch & br = static_cast<InsetBranch &>(*it);
2631 docstring const name = br.branch();
2632 if (!from_master && !params().branchlist().find(name))
2633 result.push_back(name);
2634 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2635 result.push_back(name);
2638 if (it->lyxCode() == INCLUDE_CODE) {
2639 // get buffer of external file
2640 InsetInclude const & ins =
2641 static_cast<InsetInclude const &>(*it);
2642 Buffer * child = ins.getChildBuffer();
2645 child->getUsedBranches(result, true);
2648 // remove duplicates
2653 void Buffer::updateMacroInstances() const
2655 LYXERR(Debug::MACROS, "updateMacroInstances for "
2656 << d->filename.onlyFileName());
2657 DocIterator it = doc_iterator_begin(this);
2659 DocIterator const end = doc_iterator_end(this);
2660 for (; it != end; it.forwardInset()) {
2661 // look for MathData cells in InsetMathNest insets
2662 InsetMath * minset = it.nextInset()->asInsetMath();
2666 // update macro in all cells of the InsetMathNest
2667 DocIterator::idx_type n = minset->nargs();
2668 MacroContext mc = MacroContext(this, it);
2669 for (DocIterator::idx_type i = 0; i < n; ++i) {
2670 MathData & data = minset->cell(i);
2671 data.updateMacros(0, mc);
2677 void Buffer::listMacroNames(MacroNameSet & macros) const
2682 d->macro_lock = true;
2684 // loop over macro names
2685 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2686 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2687 for (; nameIt != nameEnd; ++nameIt)
2688 macros.insert(nameIt->first);
2690 // loop over children
2691 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2692 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2693 for (; it != end; ++it)
2694 it->first->listMacroNames(macros);
2697 Buffer const * const pbuf = d->parent();
2699 pbuf->listMacroNames(macros);
2701 d->macro_lock = false;
2705 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2707 Buffer const * const pbuf = d->parent();
2712 pbuf->listMacroNames(names);
2715 MacroNameSet::iterator it = names.begin();
2716 MacroNameSet::iterator end = names.end();
2717 for (; it != end; ++it) {
2719 MacroData const * data =
2720 pbuf->getMacro(*it, *this, false);
2722 macros.insert(data);
2724 // we cannot access the original MathMacroTemplate anymore
2725 // here to calls validate method. So we do its work here manually.
2726 // FIXME: somehow make the template accessible here.
2727 if (data->optionals() > 0)
2728 features.require("xargs");
2734 Buffer::References & Buffer::references(docstring const & label)
2737 return const_cast<Buffer *>(masterBuffer())->references(label);
2739 RefCache::iterator it = d->ref_cache_.find(label);
2740 if (it != d->ref_cache_.end())
2741 return it->second.second;
2743 static InsetLabel const * dummy_il = 0;
2744 static References const dummy_refs;
2745 it = d->ref_cache_.insert(
2746 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2747 return it->second.second;
2751 Buffer::References const & Buffer::references(docstring const & label) const
2753 return const_cast<Buffer *>(this)->references(label);
2757 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2759 masterBuffer()->d->ref_cache_[label].first = il;
2763 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2765 return masterBuffer()->d->ref_cache_[label].first;
2769 void Buffer::clearReferenceCache() const
2772 d->ref_cache_.clear();
2776 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2779 //FIXME: This does not work for child documents yet.
2780 LASSERT(code == CITE_CODE, /**/);
2781 // Check if the label 'from' appears more than once
2782 vector<docstring> labels;
2784 BiblioInfo const & keys = masterBibInfo();
2785 BiblioInfo::const_iterator bit = keys.begin();
2786 BiblioInfo::const_iterator bend = keys.end();
2788 for (; bit != bend; ++bit)
2790 labels.push_back(bit->first);
2793 if (count(labels.begin(), labels.end(), from) > 1)
2796 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2797 if (it->lyxCode() == code) {
2798 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2799 docstring const oldValue = inset.getParam(paramName);
2800 if (oldValue == from)
2801 inset.setParam(paramName, to);
2807 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2808 pit_type par_end, bool full_source) const
2810 OutputParams runparams(¶ms().encoding());
2811 runparams.nice = true;
2812 runparams.flavor = params().useXetex ?
2813 OutputParams::XETEX : OutputParams::LATEX;
2814 runparams.linelen = lyxrc.plaintext_linelen;
2815 // No side effect of file copying and image conversion
2816 runparams.dryrun = true;
2819 os << "% " << _("Preview source code") << "\n\n";
2821 d->texrow.newline();
2822 d->texrow.newline();
2824 writeDocBookSource(os, absFileName(), runparams, false);
2826 // latex or literate
2827 writeLaTeXSource(os, string(), runparams, true, true);
2829 runparams.par_begin = par_begin;
2830 runparams.par_end = par_end;
2831 if (par_begin + 1 == par_end) {
2833 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2837 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2838 convert<docstring>(par_begin),
2839 convert<docstring>(par_end - 1))
2846 // output paragraphs
2848 docbookParagraphs(text(), *this, os, runparams);
2850 // latex or literate
2851 latexParagraphs(*this, text(), os, texrow, runparams);
2856 ErrorList & Buffer::errorList(string const & type) const
2858 static ErrorList emptyErrorList;
2859 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2860 if (I == d->errorLists.end())
2861 return emptyErrorList;
2867 void Buffer::updateTocItem(std::string const & type,
2868 DocIterator const & dit) const
2871 gui_->updateTocItem(type, dit);
2875 void Buffer::structureChanged() const
2878 gui_->structureChanged();
2882 void Buffer::errors(string const & err, bool from_master) const
2885 gui_->errors(err, from_master);
2889 void Buffer::message(docstring const & msg) const
2896 void Buffer::setBusy(bool on) const
2903 void Buffer::setReadOnly(bool on) const
2906 d->wa_->setReadOnly(on);
2910 void Buffer::updateTitles() const
2913 d->wa_->updateTitles();
2917 void Buffer::resetAutosaveTimers() const
2920 gui_->resetAutosaveTimers();
2924 bool Buffer::hasGuiDelegate() const
2930 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2939 class AutoSaveBuffer : public ForkedProcess {
2942 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2943 : buffer_(buffer), fname_(fname) {}
2945 virtual boost::shared_ptr<ForkedProcess> clone() const
2947 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2952 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2953 from_utf8(fname_.absFilename())));
2954 return run(DontWait);
2958 virtual int generateChild();
2960 Buffer const & buffer_;
2965 int AutoSaveBuffer::generateChild()
2967 #if defined(__APPLE__)
2968 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
2969 * We should use something else like threads.
2971 * Since I do not know how to determine at run time what is the OS X
2972 * version, I just disable forking altogether for now (JMarc)
2974 pid_t const pid = -1;
2976 // tmp_ret will be located (usually) in /tmp
2977 // will that be a problem?
2978 // Note that this calls ForkedCalls::fork(), so it's
2979 // ok cross-platform.
2980 pid_t const pid = fork();
2981 // If you want to debug the autosave
2982 // you should set pid to -1, and comment out the fork.
2983 if (pid != 0 && pid != -1)
2987 // pid = -1 signifies that lyx was unable
2988 // to fork. But we will do the save
2990 bool failed = false;
2991 FileName const tmp_ret = FileName::tempName("lyxauto");
2992 if (!tmp_ret.empty()) {
2993 buffer_.writeFile(tmp_ret);
2994 // assume successful write of tmp_ret
2995 if (!tmp_ret.moveTo(fname_))
3001 // failed to write/rename tmp_ret so try writing direct
3002 if (!buffer_.writeFile(fname_)) {
3003 // It is dangerous to do this in the child,
3004 // but safe in the parent, so...
3005 if (pid == -1) // emit message signal.
3006 buffer_.message(_("Autosave failed!"));
3010 if (pid == 0) // we are the child so...
3019 FileName Buffer::getAutosaveFilename() const
3021 // if the document is unnamed try to save in the backup dir, else
3022 // in the default document path, and as a last try in the filePath,
3023 // which will most often be the temporary directory
3026 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3027 : lyxrc.backupdir_path;
3028 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3031 string const fname = "#" + d->filename.onlyFileName() + "#";
3032 return makeAbsPath(fname, fpath);
3036 void Buffer::removeAutosaveFile() const
3038 FileName const f = getAutosaveFilename();
3044 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3046 FileName const newauto = getAutosaveFilename();
3047 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3048 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3052 // Perfect target for a thread...
3053 void Buffer::autoSave() const
3055 if (isBakClean() || isReadonly()) {
3056 // We don't save now, but we'll try again later
3057 resetAutosaveTimers();
3061 // emit message signal.
3062 message(_("Autosaving current document..."));
3063 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3067 resetAutosaveTimers();
3071 string Buffer::bufferFormat() const
3073 string format = params().documentClass().outputFormat();
3074 if (format == "latex") {
3075 if (params().useXetex)
3077 if (params().encoding().package() == Encoding::japanese)
3084 string Buffer::getDefaultOutputFormat() const
3086 if (!params().defaultOutputFormat.empty()
3087 && params().defaultOutputFormat != "default")
3088 return params().defaultOutputFormat;
3089 typedef vector<Format const *> Formats;
3090 Formats formats = exportableFormats(true);
3093 || params().useXetex
3094 || params().encoding().package() == Encoding::japanese) {
3095 if (formats.empty())
3097 // return the first we find
3098 return formats.front()->name();
3100 return lyxrc.default_view_format;
3105 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3106 string & result_file) const
3108 string backend_format;
3109 OutputParams runparams(¶ms().encoding());
3110 runparams.flavor = OutputParams::LATEX;
3111 runparams.linelen = lyxrc.plaintext_linelen;
3112 vector<string> backs = backends();
3113 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3114 // Get shortest path to format
3115 Graph::EdgePath path;
3116 for (vector<string>::const_iterator it = backs.begin();
3117 it != backs.end(); ++it) {
3118 Graph::EdgePath p = theConverters().getPath(*it, format);
3119 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3120 backend_format = *it;
3125 if (!put_in_tempdir) {
3126 // Only show this alert if this is an export to a non-temporary
3127 // file (not for previewing).
3128 Alert::error(_("Couldn't export file"), bformat(
3129 _("No information for exporting the format %1$s."),
3130 formats.prettyName(format)));
3134 runparams.flavor = theConverters().getFlavor(path);
3137 backend_format = format;
3138 // FIXME: Don't hardcode format names here, but use a flag
3139 if (backend_format == "pdflatex")
3140 runparams.flavor = OutputParams::PDFLATEX;
3143 string filename = latexName(false);
3144 filename = addName(temppath(), filename);
3145 filename = changeExtension(filename,
3146 formats.extension(backend_format));
3149 updateMacroInstances();
3151 // Plain text backend
3152 if (backend_format == "text") {
3153 runparams.flavor = OutputParams::TEXT;
3154 writePlaintextFile(*this, FileName(filename), runparams);
3157 else if (backend_format == "xhtml") {
3158 runparams.flavor = OutputParams::HTML;
3159 makeLyXHTMLFile(FileName(filename), runparams);
3160 } else if (backend_format == "lyx")
3161 writeFile(FileName(filename));
3163 else if (isDocBook()) {
3164 runparams.nice = !put_in_tempdir;
3165 makeDocBookFile(FileName(filename), runparams);
3168 else if (backend_format == format) {
3169 runparams.nice = true;
3170 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3172 } else if (!lyxrc.tex_allows_spaces
3173 && contains(filePath(), ' ')) {
3174 Alert::error(_("File name error"),
3175 _("The directory path to the document cannot contain spaces."));
3178 runparams.nice = false;
3179 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3183 string const error_type = (format == "program")
3184 ? "Build" : bufferFormat();
3185 ErrorList & error_list = d->errorLists[error_type];
3186 string const ext = formats.extension(format);
3187 FileName const tmp_result_file(changeExtension(filename, ext));
3188 bool const success = theConverters().convert(this, FileName(filename),
3189 tmp_result_file, FileName(absFileName()), backend_format, format,
3191 // Emit the signal to show the error list.
3192 if (format != backend_format) {
3194 // also to the children, in case of master-buffer-view
3195 std::vector<Buffer *> clist = getChildren();
3196 for (vector<Buffer *>::const_iterator cit = clist.begin();
3197 cit != clist.end(); ++cit)
3198 (*cit)->errors(error_type, true);
3203 if (put_in_tempdir) {
3204 result_file = tmp_result_file.absFilename();
3208 result_file = changeExtension(exportFileName().absFilename(), ext);
3209 // We need to copy referenced files (e. g. included graphics
3210 // if format == "dvi") to the result dir.
3211 vector<ExportedFile> const files =
3212 runparams.exportdata->externalFiles(format);
3213 string const dest = onlyPath(result_file);
3214 CopyStatus status = SUCCESS;
3215 for (vector<ExportedFile>::const_iterator it = files.begin();
3216 it != files.end() && status != CANCEL; ++it) {
3217 string const fmt = formats.getFormatFromFile(it->sourceName);
3218 status = copyFile(fmt, it->sourceName,
3219 makeAbsPath(it->exportName, dest),
3220 it->exportName, status == FORCE);
3222 if (status == CANCEL) {
3223 message(_("Document export cancelled."));
3224 } else if (tmp_result_file.exists()) {
3225 // Finally copy the main file
3226 status = copyFile(format, tmp_result_file,
3227 FileName(result_file), result_file,
3229 message(bformat(_("Document exported as %1$s "
3231 formats.prettyName(format),
3232 makeDisplayPath(result_file)));
3234 // This must be a dummy converter like fax (bug 1888)
3235 message(bformat(_("Document exported as %1$s"),
3236 formats.prettyName(format)));
3243 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3246 return doExport(format, put_in_tempdir, result_file);
3250 bool Buffer::preview(string const & format) const
3253 if (!doExport(format, true, result_file))
3255 return formats.view(*this, FileName(result_file), format);
3259 bool Buffer::isExportable(string const & format) const
3261 vector<string> backs = backends();
3262 for (vector<string>::const_iterator it = backs.begin();
3263 it != backs.end(); ++it)
3264 if (theConverters().isReachable(*it, format))
3270 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3272 vector<string> const backs = backends();
3273 vector<Format const *> result =
3274 theConverters().getReachable(backs[0], only_viewable, true);
3275 for (vector<string>::const_iterator it = backs.begin() + 1;
3276 it != backs.end(); ++it) {
3277 vector<Format const *> r =
3278 theConverters().getReachable(*it, only_viewable, false);
3279 result.insert(result.end(), r.begin(), r.end());
3285 vector<string> Buffer::backends() const
3288 v.push_back(bufferFormat());
3289 // FIXME: Don't hardcode format names here, but use a flag
3290 if (v.back() == "latex")
3291 v.push_back("pdflatex");
3292 v.push_back("xhtml");
3293 v.push_back("text");
3299 bool Buffer::readFileHelper(FileName const & s)
3301 // File information about normal file
3303 docstring const file = makeDisplayPath(s.absFilename(), 50);
3304 docstring text = bformat(_("The specified document\n%1$s"
3305 "\ncould not be read."), file);
3306 Alert::error(_("Could not read document"), text);
3310 // Check if emergency save file exists and is newer.
3311 FileName const e(s.absFilename() + ".emergency");
3313 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3314 docstring const file = makeDisplayPath(s.absFilename(), 20);
3315 docstring const text =
3316 bformat(_("An emergency save of the document "
3318 "Recover emergency save?"), file);
3319 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3320 _("&Recover"), _("&Load Original"),
3324 // the file is not saved if we load the emergency file.
3329 if ((res = readFile(e)) == success)
3330 str = _("Document was successfully recovered.");
3332 str = _("Document was NOT successfully recovered.");
3333 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3334 from_utf8(e.absFilename()));
3336 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3337 _("&Remove"), _("&Keep it"))) {
3340 Alert::warning(_("Emergency file deleted"),
3341 _("Do not forget to save your file now!"), true);
3346 if (!Alert::prompt(_("Delete emergency file?"),
3347 _("Remove emergency file now?"), 1, 1,
3348 _("&Remove"), _("&Keep it")))
3356 // Now check if autosave file is newer.
3357 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3359 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3360 docstring const file = makeDisplayPath(s.absFilename(), 20);
3361 docstring const text =
3362 bformat(_("The backup of the document "
3363 "%1$s is newer.\n\nLoad the "
3364 "backup instead?"), file);
3365 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3366 _("&Load backup"), _("Load &original"),
3370 // the file is not saved if we load the autosave file.
3374 // Here we delete the autosave
3385 bool Buffer::loadLyXFile(FileName const & s)
3387 if (s.isReadableFile()) {
3388 if (readFileHelper(s)) {
3389 lyxvc().file_found_hook(s);
3390 if (!s.isWritable())
3395 docstring const file = makeDisplayPath(s.absFilename(), 20);
3396 // Here we probably should run
3397 if (LyXVC::file_not_found_hook(s)) {
3398 docstring const text =
3399 bformat(_("Do you want to retrieve the document"
3400 " %1$s from version control?"), file);
3401 int const ret = Alert::prompt(_("Retrieve from version control?"),
3402 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3405 // How can we know _how_ to do the checkout?
3406 // With the current VC support it has to be,
3407 // a RCS file since CVS do not have special ,v files.
3409 return loadLyXFile(s);
3417 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3419 TeXErrors::Errors::const_iterator cit = terr.begin();
3420 TeXErrors::Errors::const_iterator end = terr.end();
3422 for (; cit != end; ++cit) {
3425 int errorRow = cit->error_in_line;
3426 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3432 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3433 } while (found && id_start == id_end && pos_start == pos_end);
3435 errorList.push_back(ErrorItem(cit->error_desc,
3436 cit->error_text, id_start, pos_start, pos_end));
3441 void Buffer::setBuffersForInsets() const
3443 inset().setBuffer(const_cast<Buffer &>(*this));
3447 void Buffer::updateLabels(UpdateScope scope, bool out) const
3449 // Use the master text class also for child documents
3450 Buffer const * const master = masterBuffer();
3451 DocumentClass const & textclass = master->params().documentClass();
3453 // keep the buffers to be children in this set. If the call from the
3454 // master comes back we can see which of them were actually seen (i.e.
3455 // via an InsetInclude). The remaining ones in the set need still be updated.
3456 static std::set<Buffer const *> bufToUpdate;
3457 if (scope == UpdateMaster) {
3458 // If this is a child document start with the master
3459 if (master != this) {
3460 bufToUpdate.insert(this);
3461 master->updateLabels(UpdateMaster, out);
3462 // Do this here in case the master has no gui associated with it. Then,
3463 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3467 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3468 if (bufToUpdate.find(this) == bufToUpdate.end())
3472 // start over the counters in the master
3473 textclass.counters().reset();
3476 // update will be done below for this buffer
3477 bufToUpdate.erase(this);
3479 // update all caches
3480 clearReferenceCache();
3483 Buffer & cbuf = const_cast<Buffer &>(*this);
3485 LASSERT(!text().paragraphs().empty(), /**/);
3488 ParIterator parit = cbuf.par_iterator_begin();
3489 updateLabels(parit, out);
3492 // TocBackend update will be done later.
3495 cbuf.tocBackend().update();
3496 if (scope == UpdateMaster)
3497 cbuf.structureChanged();
3501 static depth_type getDepth(DocIterator const & it)
3503 depth_type depth = 0;
3504 for (size_t i = 0 ; i < it.depth() ; ++i)
3505 if (!it[i].inset().inMathed())
3506 depth += it[i].paragraph().getDepth() + 1;
3507 // remove 1 since the outer inset does not count
3511 static depth_type getItemDepth(ParIterator const & it)
3513 Paragraph const & par = *it;
3514 LabelType const labeltype = par.layout().labeltype;
3516 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3519 // this will hold the lowest depth encountered up to now.
3520 depth_type min_depth = getDepth(it);
3521 ParIterator prev_it = it;
3524 --prev_it.top().pit();
3526 // start of nested inset: go to outer par
3528 if (prev_it.empty()) {
3529 // start of document: nothing to do
3534 // We search for the first paragraph with same label
3535 // that is not more deeply nested.
3536 Paragraph & prev_par = *prev_it;
3537 depth_type const prev_depth = getDepth(prev_it);
3538 if (labeltype == prev_par.layout().labeltype) {
3539 if (prev_depth < min_depth)
3540 return prev_par.itemdepth + 1;
3541 if (prev_depth == min_depth)
3542 return prev_par.itemdepth;
3544 min_depth = min(min_depth, prev_depth);
3545 // small optimization: if we are at depth 0, we won't
3546 // find anything else
3547 if (prev_depth == 0)
3553 static bool needEnumCounterReset(ParIterator const & it)
3555 Paragraph const & par = *it;
3556 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3557 depth_type const cur_depth = par.getDepth();
3558 ParIterator prev_it = it;
3559 while (prev_it.pit()) {
3560 --prev_it.top().pit();
3561 Paragraph const & prev_par = *prev_it;
3562 if (prev_par.getDepth() <= cur_depth)
3563 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3565 // start of nested inset: reset
3570 // set the label of a paragraph. This includes the counters.
3571 void Buffer::setLabel(ParIterator & it) const
3573 BufferParams const & bp = this->masterBuffer()->params();
3574 DocumentClass const & textclass = bp.documentClass();
3575 Paragraph & par = it.paragraph();
3576 Layout const & layout = par.layout();
3577 Counters & counters = textclass.counters();
3579 if (par.params().startOfAppendix()) {
3580 // FIXME: only the counter corresponding to toplevel
3581 // sectioning should be reset
3583 counters.appendix(true);
3585 par.params().appendix(counters.appendix());
3587 // Compute the item depth of the paragraph
3588 par.itemdepth = getItemDepth(it);
3590 if (layout.margintype == MARGIN_MANUAL
3591 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3592 if (par.params().labelWidthString().empty())
3593 par.params().labelWidthString(par.expandLabel(layout, bp));
3595 par.params().labelWidthString(docstring());
3598 switch(layout.labeltype) {
3600 if (layout.toclevel <= bp.secnumdepth
3601 && (layout.latextype != LATEX_ENVIRONMENT
3602 || it.text()->isFirstInSequence(it.pit()))) {
3603 counters.step(layout.counter);
3604 par.params().labelString(
3605 par.expandLabel(layout, bp));
3607 par.params().labelString(docstring());
3610 case LABEL_ITEMIZE: {
3611 // At some point of time we should do something more
3612 // clever here, like:
3613 // par.params().labelString(
3614 // bp.user_defined_bullet(par.itemdepth).getText());
3615 // for now, use a simple hardcoded label
3616 docstring itemlabel;
3617 switch (par.itemdepth) {
3619 itemlabel = char_type(0x2022);
3622 itemlabel = char_type(0x2013);
3625 itemlabel = char_type(0x2217);
3628 itemlabel = char_type(0x2219); // or 0x00b7
3631 par.params().labelString(itemlabel);
3635 case LABEL_ENUMERATE: {
3636 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3638 switch (par.itemdepth) {
3647 enumcounter += "iv";
3650 // not a valid enumdepth...
3654 // Maybe we have to reset the enumeration counter.
3655 if (needEnumCounterReset(it))
3656 counters.reset(enumcounter);
3657 counters.step(enumcounter);
3659 string const & lang = par.getParLanguage(bp)->code();
3660 par.params().labelString(counters.theCounter(enumcounter, lang));
3665 case LABEL_SENSITIVE: {
3666 string const & type = counters.current_float();
3667 docstring full_label;
3669 full_label = this->B_("Senseless!!! ");
3671 docstring name = this->B_(textclass.floats().getType(type).name());
3672 if (counters.hasCounter(from_utf8(type))) {
3673 string const & lang = par.getParLanguage(bp)->code();
3674 counters.step(from_utf8(type));
3675 full_label = bformat(from_ascii("%1$s %2$s:"),
3677 counters.theCounter(from_utf8(type), lang));
3679 full_label = bformat(from_ascii("%1$s #:"), name);
3681 par.params().labelString(full_label);
3685 case LABEL_NO_LABEL:
3686 par.params().labelString(docstring());
3690 case LABEL_TOP_ENVIRONMENT:
3691 case LABEL_CENTERED_TOP_ENVIRONMENT:
3694 par.params().labelString(par.expandLabel(layout, bp));
3700 void Buffer::updateLabels(ParIterator & parit, bool out) const
3702 LASSERT(parit.pit() == 0, /**/);
3704 // set the position of the text in the buffer to be able
3705 // to resolve macros in it. This has nothing to do with
3706 // labels, but by putting it here we avoid implementing
3707 // a whole bunch of traversal routines just for this call.
3708 parit.text()->setMacrocontextPosition(parit);
3710 depth_type maxdepth = 0;
3711 pit_type const lastpit = parit.lastpit();
3712 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3713 // reduce depth if necessary
3714 parit->params().depth(min(parit->params().depth(), maxdepth));
3715 maxdepth = parit->getMaxDepthAfter();
3717 // set the counter for this paragraph
3721 InsetList::const_iterator iit = parit->insetList().begin();
3722 InsetList::const_iterator end = parit->insetList().end();
3723 for (; iit != end; ++iit) {
3724 parit.pos() = iit->pos;
3725 iit->inset->updateLabels(parit, out);
3731 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3732 WordLangTuple & word_lang, docstring_list & suggestions) const
3736 suggestions.clear();
3737 word_lang = WordLangTuple();
3738 // OK, we start from here.
3739 DocIterator const end = doc_iterator_end(this);
3740 for (; from != end; from.forwardPos()) {
3741 // We are only interested in text so remove the math CursorSlice.
3742 while (from.inMathed()) {
3746 // If from is at the end of the document (which is possible
3747 // when leaving the mathed) LyX will crash later.
3751 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3756 // Do not increase progress when from == to, otherwise the word
3757 // count will be wrong.