1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich,
7 * Copyright 1995-2001 The LyX Team.
9 * ====================================================== */
16 #include "bufferlist.h"
17 #include "bufferview_funcs.h"
19 #include "lastfiles.h"
23 #include "BufferView.h"
25 #include "insets/insetlabel.h"
27 #include "frontends/lyx_gui.h"
28 #include "frontends/LyXView.h"
29 #include "frontends/Alert.h"
30 #include "frontends/FileDialog.h"
32 #include "support/FileInfo.h"
33 #include "support/filetools.h"
34 #include "support/path.h"
35 #include "support/systemcall.h"
36 #include "support/lstrings.h"
48 using std::back_inserter;
49 using std::istream_iterator;
53 extern BufferList bufferlist;
54 // this should be static, but I need it in buffer.C
55 bool quitting; // flag, that we are quitting the program
58 void ShowMessage(Buffer const * buf,
64 && buf && buf->getUser() && buf->getUser()->owner()) {
65 string const str = msg1 + ' ' + msg2 + ' ' + msg3;
66 buf->getUser()->owner()->message(str);
68 lyxerr << msg1 << msg2 << msg3 << endl;
79 // should be moved to lyxfunc.C
80 bool MenuWrite(BufferView * bv, Buffer * buffer)
82 if (!buffer->save()) {
83 if (Alert::askQuestion(_("Save failed. Rename and try again?"),
84 MakeDisplayPath(buffer->fileName(), 50),
85 _("(If not, document is not saved.)"))) {
86 return WriteAs(bv, buffer);
90 lastfiles->newFile(buffer->fileName());
96 // should be moved to BufferView.C
97 // Half of this func should be in LyXView, the rest in BufferView.
98 bool WriteAs(BufferView * bv, Buffer * buffer, string const & filename)
100 string fname = buffer->fileName();
101 string const oldname = fname;
103 if (filename.empty()) {
105 FileDialog fileDlg(bv->owner(),
106 _("Choose a filename to save document as"),
108 make_pair(string(_("Documents|#o#O")),
109 string(lyxrc.document_path)),
110 make_pair(string(_("Templates|#T#t")),
111 string(lyxrc.template_path)));
113 if (!IsLyXFilename(fname))
116 FileDialog::Result result =
117 fileDlg.Select(OnlyPath(fname),
118 _("*.lyx|LyX Documents (*.lyx)"),
119 OnlyFilename(fname));
121 if (result.first == FileDialog::Later)
124 fname = result.second;
129 // Make sure the absolute filename ends with appropriate suffix
130 fname = MakeAbsPath(fname);
131 if (!IsLyXFilename(fname))
136 // Same name as we have already?
137 if (!buffer->isUnnamed() && fname == oldname) {
138 if (!Alert::askQuestion(_("Same name as document already has:"),
139 MakeDisplayPath(fname, 50),
142 // Falls through to name change and save
144 // No, but do we have another file with this name open?
145 else if (!buffer->isUnnamed() && bufferlist.exists(fname)) {
146 if (Alert::askQuestion(_("Another document with same name open!"),
147 MakeDisplayPath(fname, 50),
148 _("Replace with current document?")))
150 bufferlist.close(bufferlist.getBuffer(fname));
152 // Ok, change the name of the buffer, but don't save!
153 buffer->setFileName(fname);
156 ShowMessage(buffer, _("Document renamed to '"),
157 MakeDisplayPath(fname), _("', but not saved..."));
160 } // Check whether the file exists
162 FileInfo const myfile(fname);
163 if (myfile.isOK() && !Alert::askQuestion(_("Document already exists:"),
164 MakeDisplayPath(fname, 50),
169 // Ok, change the name of the buffer
170 buffer->setFileName(fname);
172 bool unnamed = buffer->isUnnamed();
173 buffer->setUnnamed(false);
175 if (!MenuWrite(bv, buffer)) {
176 buffer->setFileName(oldname);
177 buffer->setUnnamed(unnamed);
178 ShowMessage(buffer, _("Document could not be saved!"),
179 _("Holding the old name."), MakeDisplayPath(oldname));
182 // now remove the oldname autosave file if existant!
183 removeAutosaveFile(oldname);
188 int MenuRunChktex(Buffer * buffer)
192 if (buffer->isSGML()) {
193 Alert::alert(_("Chktex does not work with SGML derived documents."));
196 ret = buffer->runChktex();
202 s = _("No warnings found.");
203 } else if (ret == 1) {
204 s = _("One warning found.");
205 t = _("Use `Navigate->Error' to find it.");
208 s += _(" warnings found.");
209 t = _("Use `Navigate->Error' to find them.");
211 Alert::alert(_("Chktex run successfully"), s, t);
213 Alert::alert(_("Error!"), _("It seems chktex does not work."));
221 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
224 if (!bufferlist.qwriteAll())
227 lastfiles->writeFile(lyxrc.lastfiles);
230 // Set a flag that we do quitting from the program,
231 // so no refreshes are necessary.
234 // close buffers first
235 bufferlist.closeAll();
237 // do any other cleanup procedures now
238 lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
240 DestroyLyXTmpDir(system_tempdir);
247 void AutoSave(BufferView * bv)
248 // should probably be moved into BufferList (Lgb)
249 // Perfect target for a thread...
251 if (!bv->available())
254 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
255 // We don't save now, but we'll try again later
256 bv->owner()->resetAutosaveTimer();
260 bv->owner()->message(_("Autosaving current document..."));
262 // create autosave filename
263 string fname = bv->buffer()->filePath();
265 fname += OnlyFilename(bv->buffer()->fileName());
268 // tmp_ret will be located (usually) in /tmp
269 // will that be a problem?
270 pid_t const pid = fork(); // If you want to debug the autosave
271 // you should set pid to -1, and comment out the
273 if (pid == 0 || pid == -1) {
274 // pid = -1 signifies that lyx was unable
275 // to fork. But we will do the save
279 string const tmp_ret = lyx::tempName(string(), "lyxauto");
280 if (!tmp_ret.empty()) {
281 bv->buffer()->writeFile(tmp_ret);
282 // assume successful write of tmp_ret
283 if (!lyx::rename(tmp_ret, fname)) {
285 // most likely couldn't move between filesystems
286 // unless write of tmp_ret failed
287 // so remove tmp file (if it exists)
288 lyx::unlink(tmp_ret);
295 // failed to write/rename tmp_ret so try writing direct
296 if (!bv->buffer()->writeFile(fname)) {
297 // It is dangerous to do this in the child,
298 // but safe in the parent, so...
300 bv->owner()->message(_("Autosave failed!"));
303 if (pid == 0) { // we are the child so...
308 bv->buffer()->markBakClean();
309 bv->owner()->resetAutosaveTimer();
314 // Copyright CHT Software Service GmbH
317 // create new file with template
320 Buffer * NewFile(string const & filename)
322 // Split argument by :
324 string tmpname = split(filename, name, ':');
325 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
326 if (name.length() == 1
327 && isalpha(static_cast<unsigned char>(name[0]))
328 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
330 name += token(tmpname, ':', 0);
331 tmpname = split(tmpname, ':');
334 lyxerr[Debug::INFO] << "Arg is " << filename
335 << "\nName is " << name
336 << "\nTemplate is " << tmpname << endl;
338 // find a free buffer
339 Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
341 lastfiles->newFile(tmpbuf->fileName());
346 // Insert ascii file (if filename is empty, prompt for one)
347 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
349 if (!bv->available())
352 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
359 // clear the selection
360 bool flag = (bv->text == bv->getLyXText());
362 bv->beforeChange(bv->text);
364 bv->getLyXText()->insertStringAsLines(bv, tmpstr);
366 bv->getLyXText()->insertStringAsParagraphs(bv, tmpstr);
369 BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
373 // Insert ascii file (if filename is empty, prompt for one)
374 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
379 FileDialog fileDlg(bv->owner(), _("Select file to insert"),
380 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
382 FileDialog::Result result = fileDlg.Select(bv->owner()->buffer()->filePath());
384 if (result.first == FileDialog::Later)
387 fname = result.second;
395 if (!fi.readable()) {
396 Alert::err_alert(_("Error! Specified file is unreadable: "),
397 MakeDisplayPath(fname, 50));
401 ifstream ifs(fname.c_str());
403 Alert::err_alert(_("Error! Cannot open specified file: "),
404 MakeDisplayPath(fname, 50));
408 ifs.unsetf(ios::skipws);
409 istream_iterator<char> ii(ifs);
410 istream_iterator<char> end;
411 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
412 // We use this until the compilers get better...
414 copy(ii, end, back_inserter(tmp));
415 string const tmpstr(tmp.begin(), tmp.end());
417 // This is what we want to use and what we will use once the
418 // compilers get good enough.
419 //string tmpstr(ii, end); // yet a reason for using std::string
420 // alternate approach to get the file into a string:
422 copy(ii, end, back_inserter(tmpstr));
429 void MenuInsertLabel(BufferView * bv, string const & arg)
432 bv->owner()->prohibitInput();
434 Paragraph * par = bv->getLyXText()->cursor.par();
435 LyXLayout_ptr layout = par->layout();
436 if (layout->latextype == LATEX_PARAGRAPH && par->previous()) {
437 Paragraph * par2 = par->previous();
439 LyXLayout_ptr const & layout2 = par2->layout();
441 if (layout2->latextype != LATEX_PARAGRAPH) {
446 string text = layout->latexname().substr(0, 3);
447 if (layout->latexname() == "theorem")
448 text = "thm"; // Create a correct prefix for prettyref
451 if (layout->latextype == LATEX_PARAGRAPH ||
452 lyxrc.label_init_length < 0)
454 string par_text = par->asString(bv->buffer(), false);
455 for (int i = 0; i < lyxrc.label_init_length; ++i) {
456 if (par_text.empty())
459 par_text = split(par_text, head, ' ');
461 text += '-'; // Is it legal to use spaces in
466 pair<bool, string> result =
467 Alert::askForText(_("Enter new label to insert:"), text);
469 label = trim(result.second);
472 if (!label.empty()) {
473 InsetCommandParams p("label", label);
474 InsetLabel * inset = new InsetLabel(p);
475 bv->insertInset(inset);
477 bv->owner()->allowInput();
481 // This function runs "configure" and then rereads lyx.defaults to
482 // reconfigure the automatic settings.
483 void Reconfigure(BufferView * bv)
485 bv->owner()->message(_("Running configure..."));
487 // Run configure in user lyx directory
490 one.startscript(Systemcall::Wait,
491 AddName(system_lyxdir, "configure"));
493 bv->owner()->message(_("Reloading configuration..."));
494 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
495 Alert::alert(_("The system has been reconfigured."),
496 _("You need to restart LyX to make use of any"),
497 _("updated document class specifications."));