Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

Saturday, June 14, 2014

Prevent Emacs from Changing Case During Completions

People where I work have the annoying habit of naming files the same as the class they define, except that the filename is capitalized differently than the class.  So the class ZooAnimal is in files zooAnimal.h and zooAnimal.cpp.  Why?  Why???

It's annoying enough when I'm trying to locate the file for a given class, but a more frequent annoyance is that when I hit M-/ to run dabbrev-expand, the out-of-the-box behavior is to change the case of what I typed to match the expansion that dabbrev found.  Using the example above, if I type "ZooAn M-/", dabbrev notices #include "zooAnimal.h", and gives me the completion "zooAnimal".  Grrr...

The dabbrev package is so fundamental that you don't need to specially enable it in your .emacs file.  In fact, I didn't even realize that's what I was using, so in my first efforts to change the completion case-folding, I was searching for variables named "*complet*", and hit a dead end.  Only on the next day did I think to C-h k M-/ to find out what function was case-folding the expansions, and that led me immediately to the variable dabbrev-case-fold-search.  The default setting for that is the symbol 'case-fold-search', which means to use the same value as case-fold-search.  Now, I do find case-folding useful on searches, either for laziness' sake, or because you don't always remember the exact capitalization of what you're looking for.  So I have case-fold-search set to 't', meaning the default behavior of dabbrev-expand was very annoying.

Solution:  either enter C-h v dabbrev-case-fold-search and click the customize link (and choose "off" for "case is significant" -- both of which are confusing descriptions in my opinion), or in your .emacs put "(setq dabbrev-case-fold-search nil)".

I purposely left dabbrev out of the post title, hoping people who are confused like me will be more likely to Google it.

Wednesday, April 10, 2013

Emacs tip: Use 'view-lossage' to answer the question "How did that happen?"

Does it ever happen that you are thumping along in emacs, and suddenly you are in a mode or buffer that you never knew about before?  You must have unintentionally hit some keystroke that caused the change, but what was it?

You can find the answer by typing C-h l (that's a little "L"). This runs view-lossage, which shows the last 100 characters typed.

For instance, this morning I was suddenly staring at a blank buffer called "ChangeLog". What is that thing? To find out, I typed C-h l. A *Help* buffer opened with a few lines of symbols. Here are the last couple lines:

C-s F I X M E C-a C-n C-n C-n C-n C-n C-n C-n
C-n C-x 2 C-x o C-x V a r C-x u C-h l

You start reading the lossage at the end.  So, at the end I can see the C-h l from invoking view-lossage.  Right before that, an undo (C-x u) to get rid of the typing I had just done into the unknown ChangeLog buffer.  Right before that, C-x V a r.  Ah, I meant to search for "Var", but I must have hit C-x instead of C-s.  This is the culprit.

So what do those keys do?  It opened a new buffer, but did it have some other harmful side-effect I want to know about?  Hit C-h k to start the describe-key function, and start typing C-x, v, a.  Before I could type the 'r', the *Help* buffer showed up and explained that I had entered the keystroke for vc-update-change-log, a function that seems like it was more useful back in the days of RCS than today, but which doesn't harm anything else.  Anyway, mystery solved!

There tend to be two situations in which I call view-lossage.  Number one is where I think, "Hmm, I don't know what I did, but it might be useful."  For that case, view-lossage lets you explore that functionality.  That was the case this morning with ChangeLog; I was curious about it but it turned out not to be useful to me.  Number two is where I think "I don't ever want that to happen again".  In that case, figure out the offending keystroke, and then disable it in your .emacs file, like this:

(global-unset-key "\C-[\C-[") ;; prefix-command
(global-unset-key "\C-x\C-p") ;; mark-page
(global-unset-key "\C-x\C-n") ;; set-goal-column

Those are typos I've made before that have annoying effects, so I just completely disable those keystrokes  (mark-page is especially nasty: it sets the mark at the end of the file, and moves the point to the beginning of the file, so there's not always an easy way to jump back to where you were in the file).

Friday, January 25, 2013

C++ Private Inheritance

For a long time I believed private inheritance was such an arcane feature that it should be avoided. In my C++ Coding Standard, 8.2 stated "Use only public inheritance." Here was my rationale:

You might find private or protected inheritance useful to save a few lines of code somewhere. But I claim you should just duplicate the lines of code, rather than couple together classes which are so different conceptually that public inheritance can't be used. They might be structurally the same today, but if they are conceptually different, that structural similarity may change over time and give you a huge headache.

I think that rationale is pretty good, but now I've decided it might be worthwhile to use private inheritance in some cases. For instance, it might make sense to inherit from some STL container class, and promote some of its lookup functions or subtypes to "public" with "using" declarations. Like this:

  class Foo : private std::map<int, Bar *> {

  public:
    typedef std::map<int, Bar *> Base;
    using Base::key_type;
    using Base::data_type;
    using Base::value_type;
    using Base::const_iterator;
    using Base::begin;
    using Base::end;
    using Base::empty;
    using Base::size;
    using Base::find;

The likelihood of the structural change mentioned above is very low in this case, and the "using" declarations -- which I'll admit I didn't know could be used that way when I first wrote the standard -- allow you to reuse worthwhile parts of the base class in a very clean and foolproof manner. Later if you realize there's another bit of functionality you want to expose publicly, you only have to write a one-liner, not a wrapper function. Meanwhile, things you might not want exposed -- like operator[]() -- stay out of the interface.

But the clincher for me is that you had better not inherit publicly from a class like std::map.  Why?  Because it doesn't have a virtual destructor.  What if someone -- for whatever reason -- ends up with a pointer to a std::map which is actually one of your Foo objects, and wants to delete it?  Only the map destructor will be called.  If ~Foo() was supposed to delete its values, that won't happen.  Similarly, public inheritance means that someone could take a pointer to a Foo, and then use map's copy constructor or assignment operator to make a simple pointer copy of the Foo, perhaps unintentionally.  Then if the original was deleted, and deleted its values, the copy would hold stale pointers.

Interestingly, I didn't seem very worried about that situation when I annotated the standard.  I wrote that you might sometimes break 8.4 -- "Destructors of base classes must be pure virtual (but implemented)." -- giving this bad advice:

If you have a memory-sensitive class where subclasses will not be used polymorphically (or do not require polymorphic destruction), you can disregard the rule and get rid of the virtual table pointer.

That seems ridiculous now.  That is actually exactly the use case for private inheritance:  you want to reuse some code, but not polymorphically.

This all came to the fore today when I considered making a class 'public std::pair', so it could model an Edge in a Boost Graph Library edge_list<>, which requires 'first' and 'second' members (at least in the iterator class you instantiate edge_list<> with).  But recently a friend of mine had twitted me on another class I wrote that inherits publicly from an STL container, so I started to think about these issues.

I'm still not sure how I'll implement my Edge class -- except that it won't be public pair -- but I see that I need to change the coding standard someday soon, to reflect the reasonable usage of private inheritance.

Tuesday, September 11, 2012

Disabling Auto-Indent in Emacs

I have to edit a C++ file at work whose indentation is so screwed up that any punctuation key I type ends up changing the indentation of the line I'm working on to something that is way out of line with the text right around it. For sanity's sake I have to M-x set-variable c-syntactic-indentation nil when I'm working on that file. The c-syntactic-indentation variable does not start out buffer-local, meaning that for the sake of the one stupid file, I have turned off the very useful feature of syntactic indentation for every file I have open in that session. So, if you are ever going to set it temporarily, make sure you have this line in your .emacs file:

  (make-variable-buffer-local 'c-syntactic-indentation)
 
While you're at it, don't you want a shortcut for the set-variable? I amused myself greatly this morning as I tried to think what shortcut I would assign this action to. The obvious mnemonics I polled with C-h k were taken: I have C-c TAB set to indent-region, C-c ; to comment-region, and C-c { set to a function to insert a skeleton class definition.  What to do?  I finally hit upon C-c (, and lo-and-behold I had already set that keystroke to toggle c-syntactic-indentation, sometime in the distant past! Here's the code:

  (global-set-key "\C-c("
                  '(lambda ()
                     (interactive)
                     (setq c-syntactic-indentation (not c-syntactic-indentation))
                     (message "c-syntactic-indentation set to %s"
                              (if c-syntactic-indentation "t" "nil"))))

Friday, June 1, 2012

Emacs: Scroll Other Window Up

It often happens that I have two related files open in one emacs frame, and I want to scroll around comparing them.  Of course to scroll back and forth in a single buffer, C-v scrolls you down, and M-v scrolls you up. (In a perverse bit of emacs jargon, C-v's function is called "scroll-up", since the text moves "up" relative to the fixed window -- even though every human wanting to look lower in the file thinks and says "scroll down, scroll down" -- and M-v's function is called "scroll-down".)

To keep two files synchronized as you peruse them, the power tool to use is M-x ediff-buffers, which sets up an interactive diff session to step through the diffs. Within ediff, a simple lowercase "v" scrolls lower in both files at once, and uppercase "V" scrolls higher. Don't forget M-x ediff-revision as a handy tool for comparing a version-controlled file to its latest revision, or for comparing two different revisions interactively.

Ediff is great, but sometimes it is too heavy-handed for the eyeballing I'm trying to do. For one thing, if one of the files contains a large section that is missing in the other, scrolling both files at once means striding through the section in one window while inching down a line at a time in the file that lacks it. Also, navigating ediff can be tedious if there are a great number of changes or reordered chunks, and once your diffs no longer line up sensibly, ediff's highlighting is simply a nuisance.

So there are the old standbys C-v and M-v, plus there is the handy M-C-v, which scrolls lower in the other window. That is, if I have a.txt and b.txt open in a single frame, and the cursor is in a.txt, then M-C-v will show a lower chunk of b.txt, to keep up with C-v in a.txt. Until today, whenever I wanted to move higher in b.txt, I didn't know of a single keystroke to do that, so I always just switched windows and used M-v. I could do C-u - M-C-v, but I never liked that.

Turns out there is a keystroke to scroll higher in b.txt without switching windows: M-C-S-v -- same keys as scrolling lower, plus the shift key. Now, M-C-v is a pretty ergonomic companion to C-v. I lean the base of my left hand on the Ctrl key, hit V with my left index finger, and keep my thumb poised over the Alt key to choose which window to scroll. The shift key just does not fit in with this scheme. With some effort, I can hold it with my left pinkie, but it's not comfortable. So my new solution is to tie that command to C-c M-C-v. True, it's not a single keystroke, but unlike the C-u solution above, it's all in the left hand, and close together without being cramped. The .emacs line is:

  (global-set-key "\C-c\M-\C-v" `scroll-other-window-down)

Yes, the command to go higher in the file -- to scroll up as we humans say -- is "scroll-other-window-down".

Thursday, January 12, 2012

gcc error: invalid use of member (did you forget the `&' ?)

Every time I have gotten the above compilation error, it has nothing to do with a missing ampersand. Instead, it is missing function-call parentheses:

  if (you_go && use->yourMember) { // WRONG!
    this->isInvalid();
  }

  if (i_go && use->myMember()) { // Oh yeah, the parens.
    continue;
  }

So don't use your member invalidly.

Thursday, January 27, 2011

Filename Expansion in Tcl

Stupid, stupid, Tcl. If you want to run a shell command with a glob filename, like *.h, you can't just do:
exec ls -l *.h

You have to explicitly tell Tcl to expand the glob, because it will pass *.h to the shell literally. But you also can't do:
exec ls -l [glob *.h]

because it will pass the entire list to the shell literally (thanks, Tcl, that's useful). You get lucky and it works if there is exactly one file matched by the glob. Otherwise ls will complain that there's no file called "a.h b.h c.h".

So what do you do? Unfortunately, if you pull up the man page for exec on the internet, it tells you a way to do this that is only syntactically valid for Tcl 8.5 or greater. For those of us living in the past, the demonic incantation you must utter is:
eval [list exec ls -l] [glob *.h]

Don't use Tcl unless you have to.

Wednesday, January 26, 2011

C++ Static No Longer Deprecated

Wow, a long-held piece of geek trivia is no longer true.

This Stack Overflow article points out that in a recent draft of the upcoming C++0x revision to the C++ standard, file-scope static declarations are no longer deprecated. For, oh, 20 years, it's been one of those finer language points that you can whip out to show your sophistication and look down on the ignorant. But between the August 2010 draft (pdf) and the November 2010 draft (pdf), the section deprecating static has been struck!

If you're unfamiliar with the issue, it's that anonymous namespaces provide a more general solution to the multiply-defined symbol problem. Instead of:


static int num = 0;
static int read_num() { return num; }


the preferred C++ way to limit visibility of global objects to file scope was:


namespace {

int num = 0;
int read_num() { return num; }

} // anonymous namespace


The rationale is that you can put other symbols you wish to hide -- like class definitions -- in such a namespace, but static doesn't help you with those. As the most general solution to the problem, namespace wins and static loses. But I suppose that 20 years of failing to break people of the static habit led to a recent change of heart.

Suits me. I had been consistently using anonymous namespaces for quite a while, both to be modern and especially since it does frequently come up that I want a type that is only used in one file. But static declarations are better for self-documenting the code, so I am happy to welcome them back.

Only problem is, I need a new piece of C++ trivia to show off with.

Wednesday, November 17, 2010

Emacs: Copy Environment Variable from Shell

Sometimes I get annoyed when my emacs session has different environment variable settings than some shell buffer I have running in the session. The most painful is when a Makefile depends on environment settings that I don't have in my .profile. Command-name completion in a shell buffer can also be painful if you have changed your path. And of course I'd like gdb to start up with the correct environment every time -- you can set the variables inside gdb, but that gets old on those days when gdb itself crashes again and again.

I kept pasting export FOO=bar into the *scratch* buffer and editing it into (setenv "FOO" "bar") and eval'ing that. After the 1000th time of doing that, I decided to automate it. Turns out emacs already has an interactive function for copying an environment variable from the shell, but you have to type in the variable name. I decided to write a little function to look for the last export, or the last echo $FOO, and copy that variable:

(defun engisneering-shell-copy-env-var ()
  (interactive)
  (let* ((expat "\\(export +\\([^=\n]+\\)=\\(.+\\)\\)")
         (echpat "\\(echo +\\$\\(.+\\)\n\\(.+\\)\\)")
         (cshpat "\\(setenv +\\([^ \n]+\\) +\\(.+\\)\\)")
         (patt (concat shell-prompt-pattern
                       "\\(" expat "\\|" echpat "\\|" cshpat "\\)")))
    (save-excursion
      (if (re-search-backward patt)
          (let* ((m (or (and (match-beginning 2) 3)
                        (and (match-beginning 5) 6) 9))
                 (var (buffer-substring (match-beginning m) (match-end m)))
                 (oldval (or (getenv var) " ")))
            (shell-copy-environment-variable var)
            (setq val (getenv var))
            (message "Old %s=%s; New %s=%s" var oldval var val))))))

Run this function inside your shell buffer, and it will search backwards for the last environment variable action and bring that variable setting into the emacs session. It's also nice because it gives you a message in the minibuffer showing the change. Add a local-set-key -- I like C-c C-v -- in your shell-mode-hook, and you're good to go.

Saturday, August 14, 2010

gcc: error: expected `)' before '&' token

Duplicate post here just to get two related error messages into page titles. That's as much SEO as I know how to do.

If you get this error from g++, and everything looks correct to you, maybe you are defining a constructor without qualifying it with the class name. See the example on this post.

gcc: error: expected unqualified-id before ')' token

I was scratching my head for a few minutes over the g++ error message in the title. Google turned up a couple of red herrings, like this one at Stack Overflow where a clueless noob #defined the name of his class.

My mistake had been to define a constructor without putting the Class:: in front of it:

    Class() // WRONG!!!
    : Super(), _duper()
    {
    }

instead of

    Class::Class()
    : Super(), _duper()
    {
    }

It wasn't as stupid as it sounds, I was cutting and pasting inlined functions into the .cpp file.

Wednesday, July 14, 2010

Can't Locate Object Method via Package

I recently got a confusing Perl error message for a line of code that I thought was a simple assignment to a hash member:

Can't locate object method "patterns" via package "objdir(/[^ ]*)?" (perhaps you forgot to load "objdir(/[^ ]*)?"?) at ./filter.pl line 24.

A Google search turned up many forum entries asking about the message, but they all had to do with open-source projects where there was indeed a package method call that had gone wrong.

After I rubbed my eyes long enough, it was obvious what I had done: left the '$' off the front of the hash reference. I had typed:

    patterns{"objdir(/[^ ]*)?"} = "dirs/objs"; # WRONG!

instead of:

    $patterns{"objdir(/[^ ]*)?"} = "dirs/objs";

I even had use strict; use warnings; on, but only got the error message. Anyway, since Google didn't help me out, let's see if this page with the error text in the title floats to the top and helps someone else out someday.

Thursday, February 4, 2010

How to Undeclare a bash Function

It took me a few minutes to figure this out, so I thought I might as well pass it along.

If you've declared a bash function, and then decided you don't really want it, either because you went ahead and implemented it as a script somewhere, or you gave it a bad name or something, you undeclare it like this:

  $ unset -f myfunc

Friday, December 11, 2009

Emacs vs. Nicer dirs

In the last post I described a nicer version of the shell dirs command that labels each directory with its position, so that you can pushd directly to the one you want.

One problem with it is that emacs shell-mode generally uses dirs to track which directory you're in. And you do want it to track directories for you. Our nicer version of dirs produces output that isn't readable to emacs.

Of course the natural solution is:

(setq shell-dirstack-query "command dirs")

to pick up the shell's builtin dirs. Sadly, you can't just throw that line into your .emacs file, because shell-mode sets shell-dirstack-query every time you start a new shell. It sets it unconditionally and globally, which is a ridiculous design flaw, but that's how it goes. There is no hook that runs after it sets the value, either.

So you're stuck with needing a workaround:
  1. Name your command something other than dirs .
  2. Use a flag on your new dirs to get the nicer behavior.
  3. Write your own emacs function to start a shell:

(defun engisneering-shell ()
(interactive)
(shell)
(setq shell-dirstack-query "command dirs"))

Tuesday, November 17, 2009

Nicer pushd, popd, and dirs

Writing up the safer, friendlier bash which command reminded me of another wrapper function that's handy to have. If you use pushd/popd to keep a stack of directories in your shell window, sometimes you want to switch to a directory far down the stack. If you want to switch to the third directory down, you do pushd +3.

The problem is, you have to count along the list of directories, since dirs, pushd, and popd all just spit out a one-line list of the stack, like this:

$ dirs
/usr/local/share ~ ~/work ~/tmp
Not an impossible task, but it can get annoying if you have some long paths in there, especially once your stack gets past two or three deep. Why not have dirs print one directory per line, and label them with their depths? To do so, add this function to your .bashrc file:

function dirs {
ds=(`command dirs`)
i=0
while [ "${ds[$i]}" != "" ]; do
echo $i: ${ds[$i]};
i=$((i+1));
done
}
Now you get more readable output:

$ dirs
0: /usr/local/share
1: ~
2: ~/work
3: ~/tmp
If you want to remove ~/work from the stack, just do popd +2.

Since pushd and popd also print the directory stack, let's add the same style of output to them:

function pushd {
if command pushd $@ > /dev/null; then
dirs
fi
}

function popd {
if command popd $@ > /dev/null; then
dirs
fi
}
One final note. In case some wacky systemwide file has aliased these commands to something else, add the following unaliasing code to the top of your .bashrc:

for func in dirs pushd popd; do
if alias $func > /dev/null 2>&1 ; then unalias $func; fi
done
Otherwise, your functions will be hidden (aliases take precedence).

PS: emacs shell-mode has a conflict with this dirs: here's how to fix it.

Monday, November 2, 2009

Keep from Killing Emacs Shell Buffers

If you're someone who lives in emacs like I do, then you probably rely on shell buffers (M-x shell) to interact with the operating system. That way you can search through output and edit history commands in a natural way that a mere terminal doesn't allow.

But occasionally I've been left kicking the wall after accidentally killing a shell buffer that had lots of work in it that I still needed. It really hurts when you accidentally kill a buffer where you're waiting for a long-running process to finish. To prevent industrial accidents like that, add a guard to kill-buffer-hook in your .emacs file:


(add-hook 'kill-buffer-hook
'(lambda()
(and
(string= "Shell" mode-name)
(or
(yes-or-no-p
(format "Kill buffer `%s'? " (buffer-name)))
(error "Aborted")))))


If you really do want to kill the shell buffer, type "yes", and you're done. But it will save you some grief if you just hit C-x k in the wrong buffer.

What's more common for me is that my eyes are on a file that I want to refresh or replace with C-x C-v (find-alternate-file), but the cursor is in a shell buffer. In that case, emacs will indeed load the alternate file, and you'll be asked "Kill buffer ` **lose**'?" Say no, then you'll have C-x b to " **lose**" (note the leading space), and rename the shell buffer to "*shell*" or whatever you had previously named it.

Monday, October 26, 2009

Bash vs. Which

The Unix which command is useful for searching your $PATH to find which version of an executable is going to run. But did you know that it doesn't always tell you the truth? For instance, it doesn't tell you when the command you're asking about is hidden by a shell builtin (or function, keyword, or alias):


$ which echo
/usr/bin/echo


which found /usr/bin/echo on your path, but echo is a shell builtin (at least in bash), so that's what will get run, not the one on the path. The GNU man page for which presents workarounds that will pick up functions and aliases, but shell builtins still slip through the cracks. The situation is even weirder on Solaris, where which is a csh shell-script, that sources your .cshrc file as part of its operation -- very strange if your shell is bash.

Clearly, which is not to be trusted. The easiest workaround, if you use bash, is the type builtin:


$ type -a echo
echo is a shell builtin
echo is /bin/echo


A slightly nicer workaround is to make a bash function for which, that uses type to do the right thing. I also like which to do an ls -l where applicable. Here's what I have in my .bashrc:


if alias which > /dev/null 2>&1; then unalias which; fi

function which {
hash -r
t=`type -t $@`

if [ -z "${t%%file*}" ]; then
for p in `type -p $@`; do
ls -l ${p};
done
else
type $@;
fi
}


Now which gives you much more information:


$ which -a wish
lrwxrwxrwx 1 root root 13 Dec 23 2008 /usr/local/bin/wish -> /usr/bin/wish*
lrwxrwxrwx 1 root root 7 Jan 8 2007 /usr/bin/wish -> wish8.3*


The unalias protects you in case some systemwide .bashrc or .profile aliases which in some way (unlikely, but good hygiene anyway). The call to hash clears the hashed function list, so that any changes to your PATH are reflected. The reason for the if statement in the function, is that we certainly want to report builtins, functions, etc., but if there are none, we can use type -p to make it easier to pass the filenames to ls -l. If there are builtins or such, we just punt and give the unaltered type output.

You can pass -a to this which if you want to see all the matches for the command, in order of precedence.

Note that this has to be a function, not a script, because running the script will source your .bashrc, which might change the PATH (all PATH changes should be in .profile, but sometimes people do it in .bashrc).

Wednesday, April 8, 2009

Extra Characters After Close-Brace

As noted previously, Tcl forces you to put open-braces "{" on the same line as the if or proc that they belong to, and forces you to use the atrocious "} else {" style.

That's appalling, but get this: it also requires a space to the right of the close-brace "}". That's just plain stupid.

Compounding the problem, the error message isn't something like "a space is required after a close-brace". Oh no. It says "extra characters after close-brace". And if the body of your if is very long, like this:
if {$tcl_is_stupid} {
  # ... many lines of code ...
  # Next line is the error
}else{
  i_eat_my_hat
}

then the error message is truncated so that you only see the part of the command that isn't broken, along with the line number of the "if", not the offending "else". As icing on the cake, in the case I was trying to help someone figure out, the error was at the top of one of Tcl's Icelandic Saga stacktraces, and the line number reported to be in error was with respect to the proc it was in, not the file.

Thankfully, Google led me to the answer, because Tcl sure didn't. I love the subtitle of that Tcl wiki page: Purpose: to discuss one of the few 'gotchas' in Tcl. Ha! What a crock!