My goal was to improve the php mode. Very often I have to define an array element. And the possible code is this:
$array['key']
$array[$key]
So, I wanted to create Emacs function, reacting upon clicking '[' key like this:
if '[' was clicked once:
print '[';
if '[' was clicked twice:
#this is for the string key
print "['']";
move the cursor between "''";
if '[' was clicked 3 times:
#this is for the variable as a key
remove "''" at the center;
#so we got [<cursor>]
I created a function:
(defvar *kb--bracket-pressed* 0)
(setq *kb--bracket-pressed* 0)
(defun bracket-pressed ()
"[ key pressed"
(interactive)
(cond
((= 0 *kb--bracket-pressed*)
(insert "[")
(setq *kb--bracket-pressed* 1)
)
((= 1 *kb--bracket-pressed*)
(insert "'']")
(backward-char 2)
(setq *kb--bracket-pressed* 2)
)
((= 2 *kb--bracket-pressed*)
(delete-char 1)
(delete-char -1)
(setq *kb--bracket-pressed* 0)
)
)
)
Then I added a function that will set *kb--bracket-pressed* = 0
when any non-bracket key was pressed:
(defun clean-bracket-pressed ()
(if (stringp (this-command-keys))
(when (and
(not (= *kb--bracket-pressed* 0))
(not (string= (this-command-keys) "["))
)
(setq *kb--bracket-pressed* 0))
)
(setq *kb--bracket-pressed* 0)
)
When opening a php file the following hook is launched:
(defun my-php-mode ()
"My php-mode customisations."
(local-set-key (kbd "[") 'bracket-pressed)
(add-hook 'pre-command-hook 'clean-bracket-pressed nil 'make-it-local)
)
(add-hook 'php-mode-hook 'my-php-mode)
For some reason clean-bracket-pressed
doesn't work correctly. When I click '[' twice, and then click any other key *kb--bracket-pressed*
is still equal to 2. While I am expecting it to become 0.