How to override global keybinding for a specific file in Emacs

When editing a large text file, harmless things in regular file can be disastrous, for example the mark-whole-buffer command that select the whole buffer will immediately crash the editor if the text file is big enough.

There is no reason to launch the dangerous command in any situation for a big file but it's possible to trigger it accidentally. It will be great to disable it for a particular file but wouldn't affect other buffers with the same major mode.

To target a specific file we should use the find-file-hook, we will match the file name in the hook function. To override the key we need to use local-set-key, we should not use define-key on the major mode keymap such as text-mode-map, it can overrides the global keymap but it affects all buffers with the same major mode.

In this case we are in text-mode and the mark-whole-buffer is bound to Ctrl + a by global-set-key. The code below will do what we want:

 
  (defun nothing ()
    (interactive)
    (message "oops!")
  )
 
  (defun disable-select-all ()  
    (when (string-match "bigfile.txt" buffer-file-name)
      (use-local-map (copy-keymap text-mode-map))
      (local-set-key "\C-a" 'nothing)))
 
  (add-hook 'find-file-hook 'disable-select-all)