]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
"Inter-word Space"
[lyx.git] / src / lyx_cb.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *          Copyright 1995 Matthias Ettrich,
7  *          Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyx_cb.h"
14 #include "lyx_main.h"
15 #include "buffer.h"
16 #include "bufferlist.h"
17 #include "bufferview_funcs.h"
18 #include "debug.h"
19 #include "lastfiles.h"
20 #include "lyxrc.h"
21 #include "lyxtext.h"
22 #include "gettext.h"
23 #include "BufferView.h"
24 #include "Lsstream.h"
25
26 #include "insets/insetlabel.h"
27
28 #include "frontends/lyx_gui.h"
29 #include "frontends/LyXView.h"
30 #include "frontends/Alert.h"
31 #include "frontends/FileDialog.h"
32
33 #include "support/FileInfo.h"
34 #include "support/filetools.h"
35 #include "support/forkedcall.h"
36 #include "support/path.h"
37 #include "support/systemcall.h"
38 #include "support/lstrings.h"
39
40 #include <fstream>
41 #include <algorithm>
42 #include <utility>
43 #include <cerrno>
44
45 using std::vector;
46 using std::ifstream;
47 using std::copy;
48 using std::endl;
49 using std::ios;
50 using std::back_inserter;
51 using std::istream_iterator;
52 using std::pair;
53 using std::make_pair;
54
55 extern BufferList bufferlist;
56 // this should be static, but I need it in buffer.C
57 bool quitting;  // flag, that we are quitting the program
58
59
60 void ShowMessage(Buffer const * buf,
61                  string const & msg1,
62                  string const & msg2,
63                  string const & msg3)
64 {
65         if (lyx_gui::use_gui
66             && buf && buf->getUser() && buf->getUser()->owner()) {
67                         string const str = msg1 + ' ' + msg2 + ' ' + msg3;
68                         buf->getUser()->owner()->message(str);
69         } else
70                 lyxerr << msg1 << msg2 << msg3 << endl;
71 }
72
73
74 //
75 // Menu callbacks
76 //
77
78 bool MenuWrite(BufferView * bv, Buffer * buffer)
79 {
80         if (buffer->save()) {
81                 lastfiles->newFile(buffer->fileName());
82                 return true;
83         }
84
85         // FIXME: we don't tell the user *WHY* the save failed !!
86
87         string const file = MakeDisplayPath(buffer->fileName(), 30);
88
89         string text = bformat(_("The document %1$s could not be saved.\n\n"
90                 "Do you want to rename the document and try again?"), file);
91         int const ret = Alert::prompt(_("Rename and save?"),
92                 text, 0, 1, _("&Rename"), _("&Cancel"));
93
94         if (ret == 0)
95                 return WriteAs(bv, buffer);
96         return false;
97 }
98
99
100
101 bool WriteAs(BufferView * bv, Buffer * buffer, string const & filename)
102 {
103         string fname = buffer->fileName();
104         string const oldname = fname;
105
106         if (filename.empty()) {
107
108                 FileDialog fileDlg(_("Choose a filename to save document as"),
109                         LFUN_WRITEAS,
110                         make_pair(string(_("Documents|#o#O")),
111                                   string(lyxrc.document_path)),
112                         make_pair(string(_("Templates|#T#t")),
113                                   string(lyxrc.template_path)));
114
115                 if (!IsLyXFilename(fname))
116                         fname += ".lyx";
117
118                 FileDialog::Result result =
119                         fileDlg.save(OnlyPath(fname),
120                                        _("*.lyx| LyX Documents (*.lyx)"),
121                                        OnlyFilename(fname));
122
123                 if (result.first == FileDialog::Later)
124                         return false;
125
126                 fname = result.second;
127
128                 if (fname.empty())
129                         return false;
130
131                 // Make sure the absolute filename ends with appropriate suffix
132                 fname = MakeAbsPath(fname);
133                 if (!IsLyXFilename(fname))
134                         fname += ".lyx";
135         } else
136                 fname = filename;
137
138         FileInfo const myfile(fname);
139         if (myfile.isOK()) {
140                 string const file = MakeDisplayPath(fname, 30);
141                 string text = bformat(_("The document %1$s already exists.\n\n"
142                         "Do you want to over-write that document?"), file);
143                 int const ret = Alert::prompt(_("Over-write document?"),
144                         text, 0, 1, _("&Over-write"), _("&Cancel"));
145
146                 if (ret == 1)
147                         return false;
148         }
149
150         // Ok, change the name of the buffer
151         buffer->setFileName(fname);
152         buffer->markDirty();
153         bool unnamed = buffer->isUnnamed();
154         buffer->setUnnamed(false);
155
156         if (!MenuWrite(bv, buffer)) {
157                 buffer->setFileName(oldname);
158                 buffer->setUnnamed(unnamed);
159                 return false;
160         }
161
162         removeAutosaveFile(oldname);
163         return true;
164 }
165
166
167 void QuitLyX()
168 {
169         lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
170
171         if (lyx_gui::use_gui) {
172                 if (!bufferlist.quitWriteAll())
173                         return;
174
175                 lastfiles->writeFile(lyxrc.lastfiles);
176         }
177
178         // Set a flag that we do quitting from the program,
179         // so no refreshes are necessary.
180         quitting = true;
181
182         // close buffers first
183         bufferlist.closeAll();
184
185         // do any other cleanup procedures now
186         lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
187
188         if (destroyDir(system_tempdir) != 0) {
189                 string msg = bformat(_("Could not remove the temporary directory %1$s"),
190                         system_tempdir);
191                 Alert::warning(_("Could not remove temporary directory"), msg);
192         }
193
194         lyx_gui::exit();
195 }
196
197
198 namespace {
199
200 class AutoSaveBuffer : public ForkedProcess {
201 public:
202         ///
203         AutoSaveBuffer(BufferView & bv, string const & fname)
204                 : bv_(bv), fname_(fname) {}
205         ///
206         virtual ForkedProcess * clone() const {
207                 return new AutoSaveBuffer(*this);
208         }
209         ///
210         int start();
211 private:
212         ///
213         virtual int generateChild();
214         ///
215         BufferView & bv_;
216         string fname_;
217 };
218
219
220 int AutoSaveBuffer::start()
221 {
222         command_ = bformat(_("Auto-saving %1$s"), fname_);
223         return runNonBlocking();
224 }
225
226
227 int AutoSaveBuffer::generateChild()
228 {
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
233         // fork.
234         if (pid == 0 || pid == -1) {
235                 // pid = -1 signifies that lyx was unable
236                 // to fork. But we will do the save
237                 // anyway.
238                 bool failed = false;
239
240                 string const tmp_ret = lyx::tempName(string(), "lyxauto");
241                 if (!tmp_ret.empty()) {
242                         bv_.buffer()->writeFile(tmp_ret);
243                         // assume successful write of tmp_ret
244                         if (!lyx::rename(tmp_ret, fname_)) {
245                                 failed = true;
246                                 // most likely couldn't move between filesystems
247                                 // unless write of tmp_ret failed
248                                 // so remove tmp file (if it exists)
249                                 lyx::unlink(tmp_ret);
250                         }
251                 } else {
252                         failed = true;
253                 }
254
255                 if (failed) {
256                         // failed to write/rename tmp_ret so try writing direct
257                         if (!bv_.buffer()->writeFile(fname_)) {
258                                 // It is dangerous to do this in the child,
259                                 // but safe in the parent, so...
260                                 if (pid == -1)
261                                         bv_.owner()->message(_("Autosave failed!"));
262                         }
263                 }
264                 if (pid == 0) { // we are the child so...
265                         _exit(0);
266                 }
267         }
268         return pid;
269 }
270
271 } // namespace anon
272
273
274 void AutoSave(BufferView * bv)
275         // should probably be moved into BufferList (Lgb)
276         // Perfect target for a thread...
277 {
278         if (!bv->available())
279                 return;
280
281         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
282                 // We don't save now, but we'll try again later
283                 bv->owner()->resetAutosaveTimer();
284                 return;
285         }
286
287         bv->owner()->message(_("Autosaving current document..."));
288
289         // create autosave filename
290         string fname = bv->buffer()->filePath();
291         fname += '#';
292         fname += OnlyFilename(bv->buffer()->fileName());
293         fname += '#';
294
295         AutoSaveBuffer autosave(*bv, fname);
296         autosave.start();
297
298         bv->buffer()->markBakClean();
299         bv->owner()->resetAutosaveTimer();
300 }
301
302
303 //
304 // Copyright CHT Software Service GmbH
305 // Uwe C. Schroeder
306 //
307 // create new file with template
308 // SERVERCMD !
309 //
310 Buffer * NewFile(string const & filename)
311 {
312         // Split argument by :
313         string name;
314         string tmpname = split(filename, name, ':');
315 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
316         if (name.length() == 1
317             && isalpha(static_cast<unsigned char>(name[0]))
318             && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
319                 name += ':';
320                 name += token(tmpname, ':', 0);
321                 tmpname = split(tmpname, ':');
322         }
323 #endif
324         lyxerr[Debug::INFO] << "Arg is " << filename
325                             << "\nName is " << name
326                             << "\nTemplate is " << tmpname << endl;
327
328         // find a free buffer
329         Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
330         if (tmpbuf)
331                 lastfiles->newFile(tmpbuf->fileName());
332         return tmpbuf;
333 }
334
335
336 // Insert ascii file (if filename is empty, prompt for one)
337 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
338 {
339         if (!bv->available())
340                 return;
341
342         string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
343         if (tmpstr.empty())
344                 return;
345
346         // clear the selection
347         bool flag = (bv->text == bv->getLyXText());
348         if (flag)
349                 bv->beforeChange(bv->text);
350         if (!asParagraph)
351                 bv->getLyXText()->insertStringAsLines(tmpstr);
352         else
353                 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
354         if (flag)
355                 bv->update(BufferView::SELECT);
356 }
357
358
359 // Insert ascii file (if filename is empty, prompt for one)
360 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
361 {
362         string fname = f;
363
364         if (fname.empty()) {
365                 FileDialog fileDlg(_("Select file to insert"),
366                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
367
368                 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
369
370                 if (result.first == FileDialog::Later)
371                         return string();
372
373                 fname = result.second;
374
375                 if (fname.empty())
376                         return string();
377         }
378
379         FileInfo fi(fname);
380
381         if (!fi.readable()) {
382                 string const error = strerror(errno);
383                 string const file = MakeDisplayPath(fname, 50);
384                 string const text = bformat(_("Could not read the specified document\n"
385                         "%1$s\ndue to the error: %2$s"), file, error);
386                 Alert::error(_("Could not read file"), text);
387                 return string();
388         }
389
390         ifstream ifs(fname.c_str());
391         if (!ifs) {
392                 string const error = strerror(errno);
393                 string const file = MakeDisplayPath(fname, 50);
394                 string const text = bformat(_("Could not open the specified document\n"
395                         "%1$s\ndue to the error: %2$s"), file, error);
396                 Alert::error(_("Could not open file"), text);
397                 return string();
398         }
399
400         ifs.unsetf(ios::skipws);
401         istream_iterator<char> ii(ifs);
402         istream_iterator<char> end;
403 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
404         // We use this until the compilers get better...
405         vector<char> tmp;
406         copy(ii, end, back_inserter(tmp));
407         string const tmpstr(tmp.begin(), tmp.end());
408 #else
409         // This is what we want to use and what we will use once the
410         // compilers get good enough.
411         //string tmpstr(ii, end); // yet a reason for using std::string
412         // alternate approach to get the file into a string:
413         string tmpstr;
414         copy(ii, end, back_inserter(tmpstr));
415 #endif
416
417         return tmpstr;
418 }
419
420
421 string const getPossibleLabel(BufferView const & bv)
422 {
423         ParagraphList::iterator pit = bv.getLyXText()->cursor.par();
424         ParagraphList & plist = bv.getLyXText()->ownerParagraphs();
425
426         LyXLayout_ptr layout = pit->layout();
427
428         if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
429                 ParagraphList::iterator pit2 = boost::prior(pit);
430
431                 LyXLayout_ptr const & layout2 = pit2->layout();
432
433                 if (layout2->latextype != LATEX_PARAGRAPH) {
434                         pit = pit2;
435                         layout = layout2;
436                 }
437         }
438
439         string text = layout->latexname().substr(0, 3);
440         if (layout->latexname() == "theorem")
441                 text = "thm"; // Create a correct prefix for prettyref
442
443         text += ':';
444         if (layout->latextype == LATEX_PARAGRAPH ||
445             lyxrc.label_init_length < 0)
446                 text.erase();
447
448         string par_text = pit->asString(bv.buffer(), false);
449         for (int i = 0; i < lyxrc.label_init_length; ++i) {
450                 if (par_text.empty())
451                         break;
452                 string head;
453                 par_text = split(par_text, head, ' ');
454                 if (i > 0)
455                         text += '-'; // Is it legal to use spaces in
456                 // labels ?
457                 text += head;
458         }
459
460         return text;
461 }
462
463
464 // This function runs "configure" and then rereads lyx.defaults to
465 // reconfigure the automatic settings.
466 void Reconfigure(BufferView * bv)
467 {
468         bv->owner()->message(_("Running configure..."));
469
470         // Run configure in user lyx directory
471         Path p(user_lyxdir);
472         Systemcall one;
473         one.startscript(Systemcall::Wait,
474                         AddName(system_lyxdir, "configure"));
475         p.pop();
476         bv->owner()->message(_("Reloading configuration..."));
477         lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
478
479         Alert::information(_("System reconfigured"),
480                 _("The system has been reconfigured.\n"
481                 "You need to restart LyX to make use of any \n"
482                 "updated document class specifications."));
483 }