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 Angus Leeming
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
20 #include "BufferList.h"
21 #include "BufferView.h"
22 #include "buffer_funcs.h"
24 #include "CutAndPaste.h"
28 #include "LaTeXFeatures.h"
35 #include "frontends/alert.h"
36 #include "frontends/Application.h"
37 #include "frontends/FileDialog.h"
38 #include "frontends/LyXView.h"
40 #include "support/FileFilterList.h"
41 #include "support/filetools.h"
42 #include "support/Forkedcall.h"
43 #include "support/fs_extras.h"
44 #include "support/lyxlib.h"
45 #include "support/Package.h"
46 #include "support/Path.h"
47 #include "support/Systemcall.h"
49 #if !defined (HAVE_FORK)
53 #include <boost/shared_ptr.hpp>
54 #include <boost/filesystem/operations.hpp>
59 using std::back_inserter;
66 using std::istream_iterator;
68 using boost::shared_ptr;
73 using support::bformat;
74 using support::FileFilterList;
75 using support::FileName;
76 using support::ForkedProcess;
77 using support::isLyXFilename;
78 using support::libFileSearch;
79 using support::makeAbsPath;
80 using support::makeDisplayPath;
81 using support::onlyFilename;
82 using support::onlyPath;
83 using support::package;
84 using support::removeAutosaveFile;
85 using support::rename;
87 using support::Systemcall;
88 using support::tempName;
89 using support::unlink;
91 namespace Alert = frontend::Alert;
92 namespace fs = boost::filesystem;
94 // this should be static, but I need it in Buffer.cpp
95 bool quitting; // flag, that we are quitting the program
101 bool menuWrite(Buffer * buffer)
103 if (buffer->save()) {
104 LyX::ref().session().lastFiles().add(FileName(buffer->fileName()));
108 // FIXME: we don't tell the user *WHY* the save failed !!
110 docstring const file = makeDisplayPath(buffer->fileName(), 30);
112 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
113 "Do you want to rename the document and "
114 "try again?"), file);
115 int const ret = Alert::prompt(_("Rename and save?"),
116 text, 0, 1, _("&Rename"), _("&Cancel"));
119 return writeAs(buffer);
125 /** Write a buffer to a new file name and rename the buffer
126 according to the new file name.
128 This function is e.g. used by menu callbacks and
129 LFUN_BUFFER_WRITE_AS.
131 If 'newname' is empty (the default), the user is asked via a
132 dialog for the buffer's new name and location.
134 If 'newname' is not empty, FileName::makeAbsPath() will indirectly
135 produce the following behaviour:
137 * If 'newname' has an absolute path, use that.
139 * If 'newname' has a relative path (or no path) and the buffer has
140 a path, that path is used as the base for 'newname'. Typically
141 this means that 'M-x buffer-write-as newname.lyx' will write to
142 the same directory as the original file.
144 * Otherwise use CWD as the base directory for 'newname'.
145 This behavour is arguably a bug, perhaps a system depedenant
146 "document directory" shoul be used instead. Note that CWD
147 isn't actually used according to a simple test on Linux.
148 Instead, it's based on '~', contrar to the documentation of
149 makeAbsPath(). Don't know what to do. *shrug*
151 Note: No checks are done on the extension etc of 'newname' when
152 it's non-empty. This may arguably also be a bug.
154 Note: The code may not code check that 'newname' is a valid for
155 the relevant file system?
157 Note: In Linux, it doesn't work with e.g. '~/file.lyx'. If it's
158 done from e.g. a buffer '/tmp/buf.lyx', it instead tries to write
159 to '/tmp/~/file.lyx'.
162 bool writeAs(Buffer * buffer, string const & newname)
164 string fname = buffer->fileName();
165 string const oldname = fname;
167 if (newname.empty()) { /// No argument? Ask user through dialog
170 FileDialog fileDlg(_("Choose a filename to save document as"),
171 LFUN_BUFFER_WRITE_AS,
172 make_pair(_("Documents|#o#O"),
173 from_utf8(lyxrc.document_path)),
174 make_pair(_("Templates|#T#t"),
175 from_utf8(lyxrc.template_path)));
177 if (!isLyXFilename(fname))
180 FileFilterList const filter (_("LyX Documents (*.lyx)"));
182 FileDialog::Result result =
183 fileDlg.save(from_utf8(onlyPath(fname)),
185 from_utf8(onlyFilename(fname)));
187 if (result.first == FileDialog::Later)
190 fname = to_utf8(result.second);
195 // Make sure the absolute filename ends with appropriate suffix
196 fname = makeAbsPath(fname).absFilename();
197 if (!isLyXFilename(fname))
201 fname = makeAbsPath(newname, onlyPath(oldname)).absFilename();
203 if (fs::exists(FileName(fname).toFilesystemEncoding())) {
204 docstring const file = makeDisplayPath(fname, 30);
205 docstring text = bformat(_("The document %1$s already "
206 "exists.\n\nDo you want to "
207 "overwrite that document?"),
209 int const ret = Alert::prompt(_("Overwrite document?"),
210 text, 0, 1, _("&Overwrite"), _("&Cancel"));
216 // Ok, change the name of the buffer
217 buffer->setFileName(fname);
219 bool unnamed = buffer->isUnnamed();
220 buffer->setUnnamed(false);
222 if (!menuWrite(buffer)) {
223 buffer->setFileName(oldname);
224 buffer->setUnnamed(unnamed);
228 removeAutosaveFile(oldname);
235 class AutoSaveBuffer : public ForkedProcess {
238 AutoSaveBuffer(BufferView & bv, FileName const & fname)
239 : bv_(bv), fname_(fname) {}
241 virtual shared_ptr<ForkedProcess> clone() const
243 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
249 virtual int generateChild();
256 int AutoSaveBuffer::start()
258 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
259 from_utf8(fname_.absFilename())));
260 return run(DontWait);
264 int AutoSaveBuffer::generateChild()
266 // tmp_ret will be located (usually) in /tmp
267 // will that be a problem?
268 pid_t const pid = fork(); // If you want to debug the autosave
269 // you should set pid to -1, and comment out the
271 if (pid == 0 || pid == -1) {
272 // pid = -1 signifies that lyx was unable
273 // to fork. But we will do the save
277 FileName const tmp_ret(tempName(FileName(), "lyxauto"));
278 if (!tmp_ret.empty()) {
279 bv_.buffer()->writeFile(tmp_ret);
280 // assume successful write of tmp_ret
281 if (!rename(tmp_ret, fname_)) {
283 // most likely couldn't move between
284 // filesystems unless write of tmp_ret
285 // failed so remove tmp file (if it
294 // failed to write/rename tmp_ret so try writing direct
295 if (!bv_.buffer()->writeFile(fname_)) {
296 // It is dangerous to do this in the child,
297 // but safe in the parent, so...
298 if (pid == -1) // emit message signal.
300 ->message(_("Autosave failed!"));
303 if (pid == 0) { // we are the child so...
313 void autoSave(BufferView * bv)
314 // should probably be moved into BufferList (Lgb)
315 // Perfect target for a thread...
320 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
321 // We don't save now, but we'll try again later
322 bv->buffer()->resetAutosaveTimers();
326 // emit message signal.
327 bv->buffer()->message(_("Autosaving current document..."));
329 // create autosave filename
330 string fname = bv->buffer()->filePath();
332 fname += onlyFilename(bv->buffer()->fileName());
335 AutoSaveBuffer autosave(*bv, FileName(fname));
338 bv->buffer()->markBakClean();
339 bv->buffer()->resetAutosaveTimers();
344 // Copyright CHT Software Service GmbH
347 // create new file with template
350 void newFile(BufferView * bv, string const & filename)
352 // Split argument by :
354 string tmpname = split(filename, name, ':');
355 LYXERR(Debug::INFO) << "Arg is " << filename
356 << "\nName is " << name
357 << "\nTemplate is " << tmpname << endl;
359 Buffer * const b = newFile(name, tmpname);
365 // Insert plain text file (if filename is empty, prompt for one)
366 void insertPlaintextFile(BufferView * bv, string const & f, bool asParagraph)
371 docstring const tmpstr =
372 getContentsOfPlaintextFile(bv, f, asParagraph);
377 Cursor & cur = bv->cursor();
378 cap::replaceSelection(cur);
381 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
383 cur.innerText()->insertStringAsLines(cur, tmpstr);
387 docstring const getContentsOfPlaintextFile(BufferView * bv, string const & f,
393 FileDialog fileDlg(_("Select file to insert"),
395 ? LFUN_FILE_INSERT_PLAINTEXT_PARA
396 : LFUN_FILE_INSERT_PLAINTEXT) );
398 FileDialog::Result result =
399 fileDlg.open(from_utf8(bv->buffer()->filePath()),
400 FileFilterList(), docstring());
402 if (result.first == FileDialog::Later)
405 fname = makeAbsPath(to_utf8(result.second));
411 if (!fs::is_readable(fname.toFilesystemEncoding())) {
412 docstring const error = from_ascii(strerror(errno));
413 docstring const file = makeDisplayPath(fname.absFilename(), 50);
414 docstring const text =
415 bformat(_("Could not read the specified document\n"
416 "%1$s\ndue to the error: %2$s"), file, error);
417 Alert::error(_("Could not read file"), text);
421 ifstream ifs(fname.toFilesystemEncoding().c_str());
423 docstring const error = from_ascii(strerror(errno));
424 docstring const file = makeDisplayPath(fname.absFilename(), 50);
425 docstring const text =
426 bformat(_("Could not open the specified document\n"
427 "%1$s\ndue to the error: %2$s"), file, error);
428 Alert::error(_("Could not open file"), text);
432 ifs.unsetf(ios::skipws);
433 istream_iterator<char> ii(ifs);
434 istream_iterator<char> end;
435 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
436 // We use this until the compilers get better...
437 std::vector<char> tmp;
438 copy(ii, end, back_inserter(tmp));
439 string const tmpstr(tmp.begin(), tmp.end());
441 // This is what we want to use and what we will use once the
442 // compilers get good enough.
443 //string tmpstr(ii, end); // yet a reason for using std::string
444 // alternate approach to get the file into a string:
446 copy(ii, end, back_inserter(tmpstr));
449 // FIXME UNICODE: We don't know the encoding of the file
450 docstring file_content = from_utf8(tmpstr);
451 if (file_content.empty()) {
452 Alert::error(_("Reading not UTF-8 encoded file"),
453 _("The file is not UTF-8 encoded.\n"
454 "It will be read as local 8Bit-encoded.\n"
455 "If this does not give the correct result\n"
456 "then please change the encoding of the file\n"
457 "to UTF-8 with a program other than LyX.\n"));
458 file_content = from_local8bit(tmpstr);
461 return normalize_c(file_content);
465 // This function runs "configure" and then rereads lyx.defaults to
466 // reconfigure the automatic settings.
467 void reconfigure(LyXView & lv)
469 // emit message signal.
470 lv.message(_("Running configure..."));
472 // Run configure in user lyx directory
473 support::Path p(package().user_support());
474 string const configure_command = package().configure_command();
476 one.startscript(Systemcall::Wait, configure_command);
478 // emit message signal.
479 lv.message(_("Reloading configuration..."));
480 lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
481 // Re-read packages.lst
482 LaTeXFeatures::getAvailable();
484 Alert::information(_("System reconfigured"),
485 _("The system has been reconfigured.\n"
486 "You need to restart LyX to make use of any\n"
487 "updated document class specifications."));