Using syntax-table information in elisp for tokenization - elisp

I would like to use elisp to tokenize the following:
variable := "The symbol \" delimits strings"; (* Comments go here *)
as:
<variable> <:=> <The symbol \" delimits strings> <;>
based on the information from the buffer's syntax-table.
I have the symbol-table setup appropriately and am currently using the following function which operates correctly except for the string constant (either returns token or nil if point is not at an identifier or one of the operators in the regex).
(defun forward-token ()
(forward-comment (point-max))
(cond
((looking-at (regexp-opt '("=" ":=" "," ";")))
(goto-char (match-end 0))
(match-string-no-properties 0))
(t (buffer-substring-no-properties
(point)
(progn (skip-syntax-forward "w_")
(point))))))
I am an elisp novice, so any pointers are appreciated.

I don't think your skip-syntax-forward use is correct for strings.
I think you need to add a cond clause like this:
((looking-at "\"")
(let* ((here (point)) (there (scan-sexps here 1)))
(goto-char there)
(buffer-substring-no-properties
(1+ here) (1- there))))
to handle string literals.

Related

emacs shell could not process % character

in emacs shell, when I type command "echo %", emacs will dead, when i cancel the command, the Message show error below:
comint-simple-send-around: Format string ends in middle of format specifier
I debug the error, because Emacs use format function, %% could work for %, but still send shell with %% character.
and below is the definition:
(defun comint-simple-send-around (simle-function proc string)
(dolist (item name-variable-map)
(let ((name (car item))
(value (symbol-value (cdr item))))
(setq string (replace-regexp-in-string name value string))
))
(message string)
(funcall simle-function proc string)
)
(advice-add #'comint-simple-send :around #'comint-simple-send-around)
The bug is in your custom code, where you're doing this:
(message string)
Where string is obviously evaluating to an invalid format string.
(message FORMAT-STRING &rest ARGS)
...
The first argument is a format control string, and the rest are data
to be formatted under control of the string. Percent sign (%), grave
accent (`) and apostrophe (') are special in the format; see
`format-message' for details. To display STRING without special
treatment, use (message "%s" STRING).

Elisp function to replace underscores for white spaces in the current line

I'm trying to write a very simple function to replace all the underscores in the current line for whites paces.
This is what I have so far
(select-current-line)
(exit-minibuffer)
(query-replace "_" " " nil (if (and transient-mark-mode mark-active) (region-beginning)) (if (and transient-mark-mode mark-active) (region-end)))
But I get the following message:
No catch for tag: exit, nil
I'm not very convinced that using query-replace in an active selection is the best way, but I am not a elisp programmer at all.
Any ideas?
Thanks
UPDATE:
Based in the answers below, this is the piece code that I ended using:
(let ((end (copy-marker (line-end-position))))
(while (re-search-forward "_" end t)
(replace-match " " nil nil)))
C-h f query-replace RET doesn't say what I wanted to quote, but C-h f perform-replace RET does:
Don't use this in your own program unless you want to query and set the mark
just as `query-replace' does. Instead, write a simple loop like this:
(while (re-search-forward \"foo[ \\t]+bar\" nil t)
(replace-match \"foobar\" nil nil))
As for limiting it to the current line, the best way to do it is to use the second arg of re-search-forward:
(let ((end (copy-marker (line-end-position))))
(while (re-search-forward \"foo[ \\t]+bar\" end t)
(replace-match \"foobar\" nil nil)))
Notice the use of copy-marker because the position of the end-of-line will keep changing as you modify the line, so you don't want to keep the position as a plain integer but as a marker (which is tied to a place in the text).
A common alternative is to go backwards (since insertion/deletions only affect positions after the change):
(end-of-line)
(let ((beg (line-beginning-position)))
(while (re-search-backward \"foo[ \\t]+bar\" beg t)
(replace-match \"foobar\" nil nil)))

How do I fix a "Wrong Type Argument: listp," error when trying to access remote file using tramp?

I am unable to access remote files in my usual way:
C-x C-f
[server]:[path][file]
and am thrown this error:
Wrong Type Argument: listp, [[server]:[path][file]
I'm not even sure how to debug this further.
any help is appreciated.
edit:
output when trying to debug:
Debugger entered: nil
(progn (debug) (ido-mode t) (progn (ad-add-advice (quote completing-read) (quote (foo nil
t (advice lambda nil (if (boundp ...) ad-do-it (setq ad-return-value ...))))) (quote
around) (quote nil)) (ad-activate (quote completing-read) nil) (quote completing-read)) (define-key global-map [(meta 120)] (function (lambda nil (interactive) (call-interactively
(intern (ido-completing-read "M-x " (all-completions "" obarray ...))))))))
(if (fboundp (quote ido-mode)) (progn (debug) (ido-mode t) (progn (ad-add-advice (quote
completing-read) (quote (foo nil t (advice lambda nil (if ... ad-do-it ...)))) (quote
around) (quote nil)) (ad-activate (quote completing-read) nil) (quote completing-read))
(define-key global-map [(meta 120)] (function (lambda nil (interactive) (call-
interactively (intern (ido-completing-read "M-x " ...))))))))
eval-buffer() ; Reading at buffer position 16103
call-interactively(eval-buffer)
(lambda nil (interactive) (call-interactively (intern (ido-completing-read "M-x " (all-
completions "" obarray (quote commandp))))))()
call-interactively((lambda nil (interactive) (call-interactively (intern (ido-completing-
read "M-x " (all-completions "" obarray (quote commandp)))))) nil nil)
recursive-edit()
debug(debug)
implement-debug-on-entry()
* ido-find-file()
call-interactively(ido-find-file nil nil)
And this from my init.el:
(require 'ido)
(if (fboundp 'ido-mode)
(progn
(debug)
(ido-mode t)
(defadvice completing-read
(around foo activate)
(if (boundp 'ido-cur-list)
ad-do-it
(setq ad-return-value
(ido-completing-read
prompt
(all-completions "" collection predicate)
nil require-match initial-input hist def))))
(define-key global-map [(meta ?x)]
(lambda ()
(interactive)
(call-interactively
(intern
(ido-completing-read "M-x " (all-completions "" obarray 'commandp))))))))
Check what command C-x C-f is bound to (use C-h k). Is it the standard binding find-file? (It doesn't sound like it.)
If not, check its interactive spec. The command is expecting to receive a list as argument, and it is instead receiving (what looks like) a string.
This is the interactive spec of find-file:
(interactive
(find-file-read-args "Find file: " (confirm-nonexistent-file-or-buffer)))
If the interactive spec of your C-x C-f command, like this one, has a non-string as its argument, then you can either M-x debug-on-entry THE-FUNCTION, where THE-FUNCTION is the function called for the argument (find-file-read-args, in the case of find-file), or wrap that argument so that the debugger is invoked:
(progn (debug) (WHATEVER-WAS-THERE-BEFORE))
Either way, the debugger will open for the interactive part of reading the file name, and you can walk through the debugger to see what goes wrong.
But probably you can figure out the problem just by inspecting the code -- the interactive spec. The argument to your command (whatever it is) is expected to be a list, but it is a string.
I would start by seeing what happens with a local file name. Do you get an error for that too?
Another thing I notice is that the error reports an extra [, in front of what you say you typed as input. That should provide a clue too. What you think it is reading is not what it has read.

How can I map an unknown list of args to start-process in elisp?

I'm finally trying to learn elisp but haven't wrapped my head around how to map an unknown list of arguments to variables dynamically.
Here's a working function that passes up to three arguments to start-process. But I would like to pass an infinite number of args to the function.
(defun create-drush-buffer (command &rest a)
(if (locate-dominating-file default-directory "includes/bootstrap.inc")
(progn
(setq opt1 (car a))
(setq opt2 (cadr a))
(setq opt3 (caddr a))
(setq allopt (concat opt1 " " opt2 " " opt3))
(setq b-name (concat "*drush " command " " allopt "*"))
(if (buffer-live-p b-name)
(switch-to-buffer b-name)
(setq d-buffer (get-buffer-create b-name))
(with-current-buffer d-buffer
(goto-char (point-min))
(view-mode 1)
(hl-line-mode 1)
(if opt3
(start-process "drush" (current-buffer) drupal-drush-program
command
opt1
opt2
opt3)
(if opt2
(start-process "drush" (current-buffer)
drupal-drush-program
command
opt1
opt2)
(if opt1
(start-process "drush" (current-buffer)
drupal-drush-program
command
opt1)
(start-process "drush" (current-buffer)
drupal-drush-program
command))))
(shrink-window-if-larger-than-buffer))
(switch-to-buffer d-buffer)))
(message (concat default-directory " is not a drupal project"))))
Here's an example of a calling function I would like to work with create-drush-buffer.
(defun drush-sql-sync ()
(interactive)
(create-drush-buffer
"sql-sync"
"-y"
"-d"
"-v"
"#cu.wstage1-education"
"#cu.local-education"))
How can I achieve this and make my code less redundant? Any help with code or even steering me to relevant documentation appreciated.
You can use apply:
(apply FUNCTION &rest ARGUMENTS)
Call FUNCTION with our remaining args, using our last arg as list of
args. Then return the value FUNCTION returns. Thus, (apply '+ 1 2 '(3
4)) returns 10.
This way, you could call start-process using something like:
(apply 'start-process "drush" (current-buffer)
drupal-drush-program
command
a)
As a side note, you should not create temporary variables using setq, as this creates or modified global variables (if no local ones with the name exists). Instead, use let.
Good luck with your elisp projects!

Open a file at line with "filename:line" syntax

Very often, compilations errors are displayed with the file:line syntax.
It would be nice to copy-paste this directly to open the file at the right line.
Emacs already has some mode to handle this in buffers (compile-mode, iirc), but I would like to have this available from the shell command line, since I use the standard shell most of the time outside of emacs.
Any idea how to tweak emacs to learn file:line syntax to open file at line line? (obviously, if file:line really exists on disk, it should be opened preferably)
You can do this using emacsclient. e.g. to open FILE at line 4, column 3 in a new frame:
emacsclient +4:3 FILE
Leave off the :3 to simply open the file at line 4.
I have the following in my .emacs, but I haven't found it as useful as I thought it would be.
;; Open files and goto lines like we see from g++ etc. i.e. file:line#
;; (to-do "make `find-file-line-number' work for emacsclient as well")
;; (to-do "make `find-file-line-number' check if the file exists")
(defadvice find-file (around find-file-line-number
(filename &optional wildcards)
activate)
"Turn files like file.cpp:14 into file.cpp and going to the 14-th line."
(save-match-data
(let* ((matched (string-match "^\\(.*\\):\\([0-9]+\\):?$" filename))
(line-number (and matched
(match-string 2 filename)
(string-to-number (match-string 2 filename))))
(filename (if matched (match-string 1 filename) filename)))
ad-do-it
(when line-number
;; goto-line is for interactive use
(goto-char (point-min))
(forward-line (1- line-number))))))
I suggest to add following code in your emacs config:
(defadvice server-visit-files (before parse-numbers-in-lines (files proc &optional nowait) activate)
"looks for filenames like file:line or file:line:position and reparses name in such manner that position in file"
(ad-set-arg 0
(mapcar (lambda (fn)
(let ((name (car fn)))
(if (string-match "^\\(.*?\\):\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?$" name)
(cons
(match-string 1 name)
(cons (string-to-number (match-string 2 name))
(string-to-number (or (match-string 3 name) "")))
)
fn))) files))
)
by now you can open file with a line number right from command line like this:
emacsclient filename:linenumber:position
P.S. I hope i'm not too late with my answer.
And here is my go at it. Calls the original find-file-at-point
(defun find-file-at-point-with-line()
"if file has an attached line num goto that line, ie boom.rb:12"
(interactive)
(setq line-num 0)
(save-excursion
(search-forward-regexp "[^ ]:" (point-max) t)
(if (looking-at "[0-9]+")
(setq line-num (string-to-number (buffer-substring (match-beginning 0) (match-end 0))))))
(find-file-at-point)
(if (not (equal line-num 0))
(goto-line line-num)))
You can use a bash script:
#! /bin/bash
file=$(awk '{sub(/:[0-9]*$/,"")}1' <<< "$1")
line=$(awk '{sub(/^.*:/,"")}1' <<< "$1")
emacs --no-splash "+$line" "$file" &
If you call this script for openline and you get an error message, e.g.
Error: file.cpp:1046
you can do
openline file.cpp:1046
to open the file.cpp in Emacs at line 1046..
Another version of Ivan Andrus' nice find-file advice which does both line + optional column number, as you see in node and coffeescript errors:
;; Open files and go places like we see from error messages, i e: path:line:col
;; (to-do "make `find-file-line-number' work for emacsclient as well")
;; (to-do "make `find-file-line-number' check if the file exists")
(defadvice find-file (around find-file-line-number
(path &optional wildcards)
activate)
"Turn files like file.js:14:10 into file.js and going to line 14, col 10."
(save-match-data
(let* ((match (string-match "^\\(.*?\\):\\([0-9]+\\):?\\([0-9]*\\)$" path))
(line-no (and match
(match-string 2 path)
(string-to-number (match-string 2 path))))
(col-no (and match
(match-string 3 path)
(string-to-number (match-string 3 path))))
(path (if match (match-string 1 path) path)))
ad-do-it
(when line-no
;; goto-line is for interactive use
(goto-char (point-min))
(forward-line (1- line-no))
(when (> col-no 0)
(forward-char (1- col-no)))))))
Emacs 25 does not use defadvice anymore. Refs.
So here is the version updated to the new syntax:
(defun find-file--line-number (orig-fun filename &optional wildcards)
"Turn files like file.cpp:14 into file.cpp and going to the 14-th line."
(save-match-data
(let* ((matched (string-match "^\\(.*\\):\\([0-9]+\\):?$" filename))
(line-number (and matched
(match-string 2 filename)
(string-to-number (match-string 2 filename))))
(filename (if matched (match-string 1 filename) filename)))
(apply orig-fun (list filename wildcards))
(when line-number
;; goto-line is for interactive use
(goto-char (point-min))
(forward-line (1- line-number))))))
(advice-add 'find-file :around #'find-file--line-number)
This works if you call open file from inside emacs (C-x C-f), but not works anymore from command line, it seems that emacs 25 is not using find-file when you call it from command line and I don't know how to debug this kind of thing.
You talk about pasting to open a file (I assume you mean at a find file prompt inside of emacs) and also doing something from the command line. If you want to copy & paste then you need to do something like what Ivan showed with the defadvice. If you want something from the command line you can do the following. I've adapted this from something I did a year ago with an emacs:// URI handler (for use from within Firefox):
Put this in your .emacs file:
(defun emacs-uri-handler (uri)
"Handles emacs URIs in the form: emacs:///path/to/file/LINENUM"
(save-match-data
(if (string-match "emacs://\\(.*\\)/\\([0-9]+\\)$" uri)
(let ((filename (match-string 1 uri))
(linenum (match-string 2 uri)))
(while (string-match "\\(%20\\)" filename)
(setq filename (replace-match " " nil t filename 1)))
(with-current-buffer (find-file filename)
(goto-line (string-to-number linenum))))
(beep)
(message "Unable to parse the URI <%s>" uri))))
and then create a shell script in your path (I called mine 'emacsat'):
#!/bin/bash
emacsclient --no-wait -e "(emacs-uri-handler \"emacs://$1/${2:-1}\")"
A DOS batch script would look similar, but I don't know how to do default values (though I'm pretty sure you can do it).
See How to configure firefox to run emacsclientw on certain links? for further instructions if you want to integrate with Firefox, too.
To return42's code, added column number support, and cleaned up case where column number is present, and line number is sought.
;; find file at point, jump to line no.
;; ====================================
(require 'ffap)
(defun find-file-at-point-with-line (&optional filename)
"Opens file at point and moves point to line specified next to file name."
(interactive)
(let* ((filename (or filename (if current-prefix-arg (ffap-prompter) (ffap-guesser))))
(line-number
(and (or (looking-at ".* line \\(\[0-9\]+\\)")
(looking-at "[^:]*:\\(\[0-9\]+\\)"))
(string-to-number (match-string-no-properties 1))))
(column-number
(or
(and (looking-at "[^:]*:\[0-9\]+:\\(\[0-9\]+\\)")
(string-to-number (match-string-no-properties 1)))
(let 'column-number 0))))
(message "%s --> %s:%s" filename line-number column-number)
(cond ((ffap-url-p filename)
(let (current-prefix-arg)
(funcall ffap-url-fetcher filename)))
((and line-number
(file-exists-p filename))
(progn (find-file-other-window filename)
;; goto-line is for interactive use
(goto-char (point-min))
(forward-line (1- line-number))
(forward-char column-number)))
((and ffap-pass-wildcards-to-dired
ffap-dired-wildcards
(string-match ffap-dired-wildcards filename))
(funcall ffap-directory-finder filename))
((and ffap-dired-wildcards
(string-match ffap-dired-wildcards filename)
find-file-wildcards
;; Check if it's find-file that supports wildcards arg
(memq ffap-file-finder '(find-file find-alternate-file)))
(funcall ffap-file-finder (expand-file-name filename) t))
((or (not ffap-newfile-prompt)
(file-exists-p filename)
(y-or-n-p "File does not exist, create buffer? "))
(funcall ffap-file-finder
;; expand-file-name fixes "~/~/.emacs" bug sent by CHUCKR.
(expand-file-name filename)))
;; User does not want to find a non-existent file:
((signal 'file-error (list "Opening file buffer"
"no such file or directory"
filename))))))
I made a little rewrite of the find-file-at-point function.
If there is a line number match, the file will be opened within an other window and the courser will be placed in this line. If no line number match, do what ffap normally does ...
;; find file at point, jump to line no.
;; ====================================
(require 'ffap)
(defun find-file-at-point-with-line (&optional filename)
"Opens file at point and moves point to line specified next to file name."
(interactive)
(let* ((filename (or filename (ffap-prompter)))
(line-number
(and (or (looking-at ".* line \\(\[0-9\]+\\)")
(looking-at ".*:\\(\[0-9\]+\\):"))
(string-to-number (match-string-no-properties 1)))))
(message "%s --> %s" filename line-number)
(cond ((ffap-url-p filename)
(let (current-prefix-arg)
(funcall ffap-url-fetcher filename)))
((and line-number
(file-exists-p filename))
(progn (find-file-other-window filename)
(goto-line line-number)))
((and ffap-pass-wildcards-to-dired
ffap-dired-wildcards
(string-match ffap-dired-wildcards filename))
(funcall ffap-directory-finder filename))
((and ffap-dired-wildcards
(string-match ffap-dired-wildcards filename)
find-file-wildcards
;; Check if it's find-file that supports wildcards arg
(memq ffap-file-finder '(find-file find-alternate-file)))
(funcall ffap-file-finder (expand-file-name filename) t))
((or (not ffap-newfile-prompt)
(file-exists-p filename)
(y-or-n-p "File does not exist, create buffer? "))
(funcall ffap-file-finder
;; expand-file-name fixes "~/~/.emacs" bug sent by CHUCKR.
(expand-file-name filename)))
;; User does not want to find a non-existent file:
((signal 'file-error (list "Opening file buffer"
"no such file or directory"
filename))))))
If you have an old version of the ffap (2008) you should update your emacs or apply
an other small patch ...
--- Emacs/lisp/ffap.el
+++ Emacs/lisp/ffap.el
## -1170,7 +1170,7 ## which may actually result in an url rather than a filename."
;; remote, you probably already have a connection.
((and (not abs) (ffap-file-exists-string name)))
;; Try stripping off line numbers; good for compilation/grep output.
- ((and (not abs) (string-match ":[0-9]" name)
+ ((and (string-match ":[0-9]" name)
(ffap-file-exists-string (substring name 0 (match-beginning 0)))))
;; Try stripping off prominent (non-root - #) shell prompts
Here is a zsh function that works if you put it into your .zshrc file.
Since I'm running my code in zsh usually, and this is where i see the errors. Kudos to #sanityinc for the emacs part. Just thought this should be on google.
emn () {
blah=$1
filen=(${(s.:.)blah})
/Applications/Emacs.app/Contents/MacOS/Emacs +$filen[2] $filen[1] &
}
Use like emn /long/stack/error.rb:123
I've modified ivan-andrus defadvice so it works with emacsclient:
(defadvice find-file-noselect (around find-file-noselect-at-line
(filename &optional nowarn rawfile wildcards)
activate)
"Turn files like file.cpp:14 into file.cpp and going to the 14-th line."
(save-match-data
(let* ((matched (string-match "^\\(.*\\):\\([0-9]+\\):?$" filename))
(line-number (and matched
(match-string 2 filename)
(string-to-number (match-string 2 filename))))
(filename (if matched (match-string 1 filename) filename))
(buffer-name ad-do-it))
(when line-number
(with-current-buffer buffer-name
(goto-char (point-min))
(forward-line (1- line-number)))))))
I use this a lot, I made it with command-line-1:
;;;; Open files and goto lines like we see from g++ etc. i.e. file:line#
(defun command-line-1--line-number (orig-fun args)
(setq new-args ())
(dolist (f args)
(setq new-args
(append new-args
(if (string-match "^\\(.*\\):\\([0-9]+\\):?$" f)
(list (concat "+" (match-string 2 f))
(match-string 1 f))
(list f)))))
(apply orig-fun (list new-args)))
(advice-add 'command-line-1 :around #'command-line-1--line-number)

Resources