[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How can I write this function better?
From: |
John Mastro |
Subject: |
Re: How can I write this function better? |
Date: |
Tue, 14 Mar 2017 10:48:27 -0700 |
user <user0012@cocaine.ninja> wrote:
> Hello help-gnu-emacs, I'm looking for pointers with my luser-0x0
> function. I'm sure there are better ways I could write this. I'm not
> asking to have you rewrite it for me, that'd be rude of me, but rather
> what I should to look at, such as documentation or learning new
> constructs etc. I'm _very_ new to programming and Lisp (learning Lisp
> and Forth as my first languages; quite fun). An explanation, which I
> first wrote for myself, is below the code.
Here was my first thought on how I would personally write it. I wouldn't
say it's better (they achieve the same thing) but perhaps it will give
you an idea or two.
The things I changed were:
- Make the region beginning and end positions arguments to the function
(which default to the region-or-buffer) when called interactively
- Only call `file-name-extension' when the buffer is visiting a file,
otherwise just use ".txt"
- Call `write-region' directly (rather than via `apply')
- Use `call-process' with a destination buffer rather than
`start-process' with a sentinel
- Delete the temporary file at the end unless an optional argument
says not to
Regarding the last point, `start-process' does have an advantage, which
is that the process is asynchronous. However, that may not matter for
this, if the upload will proceed quickly and/or you would wait for it to
finish before moving on anyway. For instance, if the upload takes a
while, then it might be odd to have its output added to your kill-ring
at some point later anyway.
Here's the code (lightly tested):
(defun luser-0x0 (beg end &optional keep-file)
"Upload region from BEG to END https://0x0.st.
When called interactively, BEG and END default to the bounds of
the region if active, or the buffer otherwise. If KEEP-FILE is
non-nil, do not delete the temporary file that was uploaded."
(interactive
(if (use-region-p)
(list (region-beginning) (region-end))
(list (point-min) (point-max))))
(let ((file (make-temp-file "0x0" nil
(if (buffer-file-name)
(file-name-extension (buffer-file-name) t)
".txt"))))
(write-region beg end file)
(with-temp-buffer
(call-process "curl" nil (current-buffer) nil
"-F" (concat "file=@" file) "https://0x0.st")
(kill-new (message "%s" (buffer-string))))
(if keep-file
file
(delete-file file t)
nil)))
Hope that helps
John