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 bool writeAs(Buffer * buffer, string const & newname)
127 string fname = buffer->fileName();
128 string const oldname = fname;
130 if (newname.empty()) {
133 FileDialog fileDlg(_("Choose a filename to save document as"),
134 LFUN_BUFFER_WRITE_AS,
135 make_pair(_("Documents|#o#O"),
136 from_utf8(lyxrc.document_path)),
137 make_pair(_("Templates|#T#t"),
138 from_utf8(lyxrc.template_path)));
140 if (!isLyXFilename(fname))
143 FileFilterList const filter (_("LyX Documents (*.lyx)"));
145 FileDialog::Result result =
146 fileDlg.save(from_utf8(onlyPath(fname)),
148 from_utf8(onlyFilename(fname)));
150 if (result.first == FileDialog::Later)
153 fname = to_utf8(result.second);
158 // Make sure the absolute filename ends with appropriate suffix
159 fname = makeAbsPath(fname).absFilename();
160 if (!isLyXFilename(fname))
165 FileName const filename(fname);
166 if (fs::exists(filename.toFilesystemEncoding())) {
167 docstring const file = makeDisplayPath(fname, 30);
168 docstring text = bformat(_("The document %1$s already "
169 "exists.\n\nDo you want to "
170 "overwrite that document?"),
172 int const ret = Alert::prompt(_("Overwrite document?"),
173 text, 0, 1, _("&Overwrite"), _("&Cancel"));
179 // Ok, change the name of the buffer
180 buffer->setFileName(fname);
182 bool unnamed = buffer->isUnnamed();
183 buffer->setUnnamed(false);
185 if (!menuWrite(buffer)) {
186 buffer->setFileName(oldname);
187 buffer->setUnnamed(unnamed);
191 removeAutosaveFile(oldname);
198 class AutoSaveBuffer : public ForkedProcess {
201 AutoSaveBuffer(BufferView & bv, FileName const & fname)
202 : bv_(bv), fname_(fname) {}
204 virtual shared_ptr<ForkedProcess> clone() const
206 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
212 virtual int generateChild();
219 int AutoSaveBuffer::start()
221 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
222 from_utf8(fname_.absFilename())));
223 return run(DontWait);
227 int AutoSaveBuffer::generateChild()
229 // tmp_ret will be located (usually) in /tmp
230 // will that be a problem?
231 pid_t const pid = fork(); // If you want to debug the autosave
232 // you should set pid to -1, and comment out the
234 if (pid == 0 || pid == -1) {
235 // pid = -1 signifies that lyx was unable
236 // to fork. But we will do the save
240 FileName const tmp_ret(tempName(FileName(), "lyxauto"));
241 if (!tmp_ret.empty()) {
242 bv_.buffer()->writeFile(tmp_ret);
243 // assume successful write of tmp_ret
244 if (!rename(tmp_ret, fname_)) {
246 // most likely couldn't move between
247 // filesystems unless write of tmp_ret
248 // failed so remove tmp file (if it
257 // failed to write/rename tmp_ret so try writing direct
258 if (!bv_.buffer()->writeFile(fname_)) {
259 // It is dangerous to do this in the child,
260 // but safe in the parent, so...
261 if (pid == -1) // emit message signal.
263 ->message(_("Autosave failed!"));
266 if (pid == 0) { // we are the child so...
276 void autoSave(BufferView * bv)
277 // should probably be moved into BufferList (Lgb)
278 // Perfect target for a thread...
283 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
284 // We don't save now, but we'll try again later
285 bv->buffer()->resetAutosaveTimers();
289 // emit message signal.
290 bv->buffer()->message(_("Autosaving current document..."));
292 // create autosave filename
293 string fname = bv->buffer()->filePath();
295 fname += onlyFilename(bv->buffer()->fileName());
298 AutoSaveBuffer autosave(*bv, FileName(fname));
301 bv->buffer()->markBakClean();
302 bv->buffer()->resetAutosaveTimers();
307 // Copyright CHT Software Service GmbH
310 // create new file with template
313 void newFile(BufferView * bv, string const & filename)
315 // Split argument by :
317 string tmpname = split(filename, name, ':');
318 LYXERR(Debug::INFO) << "Arg is " << filename
319 << "\nName is " << name
320 << "\nTemplate is " << tmpname << endl;
322 Buffer * const b = newFile(name, tmpname);
328 // Insert plain text file (if filename is empty, prompt for one)
329 void insertPlaintextFile(BufferView * bv, string const & f, bool asParagraph)
334 docstring const tmpstr =
335 getContentsOfPlaintextFile(bv, f, asParagraph);
340 Cursor & cur = bv->cursor();
341 cap::replaceSelection(cur);
344 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
346 cur.innerText()->insertStringAsLines(cur, tmpstr);
350 docstring const getContentsOfPlaintextFile(BufferView * bv, string const & f,
356 FileDialog fileDlg(_("Select file to insert"),
358 ? LFUN_FILE_INSERT_PLAINTEXT_PARA
359 : LFUN_FILE_INSERT_PLAINTEXT) );
361 FileDialog::Result result =
362 fileDlg.open(from_utf8(bv->buffer()->filePath()),
363 FileFilterList(), docstring());
365 if (result.first == FileDialog::Later)
368 fname = makeAbsPath(to_utf8(result.second));
374 if (!fs::is_readable(fname.toFilesystemEncoding())) {
375 docstring const error = from_ascii(strerror(errno));
376 docstring const file = makeDisplayPath(fname.absFilename(), 50);
377 docstring const text =
378 bformat(_("Could not read the specified document\n"
379 "%1$s\ndue to the error: %2$s"), file, error);
380 Alert::error(_("Could not read file"), text);
384 ifstream ifs(fname.toFilesystemEncoding().c_str());
386 docstring const error = from_ascii(strerror(errno));
387 docstring const file = makeDisplayPath(fname.absFilename(), 50);
388 docstring const text =
389 bformat(_("Could not open the specified document\n"
390 "%1$s\ndue to the error: %2$s"), file, error);
391 Alert::error(_("Could not open file"), text);
395 ifs.unsetf(ios::skipws);
396 istream_iterator<char> ii(ifs);
397 istream_iterator<char> end;
398 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
399 // We use this until the compilers get better...
400 std::vector<char> tmp;
401 copy(ii, end, back_inserter(tmp));
402 string const tmpstr(tmp.begin(), tmp.end());
404 // This is what we want to use and what we will use once the
405 // compilers get good enough.
406 //string tmpstr(ii, end); // yet a reason for using std::string
407 // alternate approach to get the file into a string:
409 copy(ii, end, back_inserter(tmpstr));
412 // FIXME UNICODE: We don't know the encoding of the file
413 docstring file_content = from_utf8(tmpstr);
414 if (file_content.empty()) {
415 Alert::error(_("Reading not UTF-8 encoded file"),
416 _("The file is not UTF-8 encoded.\n"
417 "It will be read as local 8Bit-encoded.\n"
418 "If this does not give the correct result\n"
419 "then please change the encoding of the file\n"
420 "to UTF-8 with a program other than LyX.\n"));
421 file_content = from_local8bit(tmpstr);
424 return normalize_c(file_content);
428 // This function runs "configure" and then rereads lyx.defaults to
429 // reconfigure the automatic settings.
430 void reconfigure(LyXView & lv)
432 // emit message signal.
433 lv.message(_("Running configure..."));
435 // Run configure in user lyx directory
436 support::Path p(package().user_support());
437 string const configure_command = package().configure_command();
439 one.startscript(Systemcall::Wait, configure_command);
441 // emit message signal.
442 lv.message(_("Reloading configuration..."));
443 lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
444 // Re-read packages.lst
445 LaTeXFeatures::getAvailable();
447 Alert::information(_("System reconfigured"),
448 _("The system has been reconfigured.\n"
449 "You need to restart LyX to make use of any\n"
450 "updated document class specifications."));