Category Archives: geek

Recording from Emacs Hangout #2

Thanks to Cameron Desautels for hosting this one! =D I totally like Emacs Hangouts. We should have more of them.

  • tips for showing people how awesome magit is: partial staging, history browsing, diff viewing and jumping to the source file
  • org-present, org-babel, org inline images, source code highlighting
  • themes
  • magit new version, dealing with problems, history browsing, subcommands (:), remoting (M), interactive rebase (E), new features, Wazzup – shows you branch differences (w)
  • magit workflows, customization (ex: full-screen), fun with bisecting
  • use-package, delaying configuration
  • Dvorak, keyboard customization
  • evil-mode
  • selective display – folds everything beyond an indentation depth
  • managing large screens – folding, follow mode, etc.
  • projectile-mode
  • flx ido
  • ace-jump-mode – binding to C-0
  • Emacs on Mac OS X, terminal Emacs, sharing clipboard (pbcopy)
  • binding things to C-number; M-number, prefix arguments

Using Org Mode to keep a process journal

I (re)started keeping a journal in Org Mode – chronologically-ordered snippets on what I’m doing, how I’m doing things, and how I’m thinking of improving. I’d mentioned the idea previously on my blog. In this post, I want to share the workflow and configuration that makes it easier for me to log entries.

When I’m on my personal computer, I use Org Mode’s org-capture command to quickly capture notes. I’ve bound org-capture to C-c r, a remnant from the way I still think of it as related to the even older org-remember and remember functions. Anyway, org-capture allows you to define several org-capture-templates, and it will display these templates in a menu so that you can choose from them when creating your note.

Here’s the template I’ve been using for my captures:

(setq org-capture-templates
      '(;; other entries
        ("j" "Journal entry" plain
         (file+datetree+prompt "~/personal/journal.org")
         "%K - %a\n%i\n%?\n")
        ;; other entries
        ))

This stores a link to the currently-clocked task and to whatever context I was looking at when I started the journal entry. It also copies the active region (if any), then positions my cursor after that text. Unlike the default template, this template does not include an Org heading. That way, I don’t have to think of a headline, and I can also just clear the buffer and close the window without adding lots of half-filled-in entries in my journal.

The file+datetree+prompt keyword means that the entries will be stored in ~/personal/journal.org in an outline corresponding to the year, month, and day that I specify. This makes it easy to write an entry for today or for any particular date. For example, I often find myself adding more notes for the previous day (-1) because of something I remembered.

I’m thinking of making Fridays my day for reviewing what I’ve learned and writing up more notes. With the date-tree structure, it’s easy to review my notes by day and look for little things to harvest.

If I know I want to revisit something, I can also add a TODO right in the journal entries using the regular Org syntax or as a keyword that I can search for. If it’s a separate heading (ex: *** TODO Take over the world), I can use org-refile to move it to its proper project.

When I want to flesh out those rough notes into a blog post, I can copy the entry to my blog post outline, fill in the details, and then use org2blog/wp-post-subtree to post it to WordPress. Alternatively, I might edit my rough notes in-place to make them ready to post, and then post them directly from that buffer (possibly changing the heading).

Since I’m not always on my personal computer, I need to be able to pull in notes from elsewhere. I can add quick notes to Evernote on my phone. So far, I’ve been okay with copying snippets manually. If I find that I’m creating lots of notes, though, I might look into reusing the code that I have for building my weekly review list from Evernote notes.

Time-wise, I find that spending 15-30 minutes at the end of the day helps me braindump the key points. If I take little writing breaks throughout the day, that helps me capture more details (especially in terms of development or technical troubleshooting). Re-reading my notes is part of my regular weekly review process, so it’s pretty quick (plus a little more time if I’m writing longer blog posts).

That’s how Org Mode helps me keep a process journal. It’s great to be able to quickly write notes in the same thing you use to do everything else, and to tweak your workflow. Whee!

Beginner web dev tip: Use Inspect Element to learn more about HTML and CSS on a page

One of the neat things about learning web development is that the Web is full of examples you can learn from. You can use your browser’s View Page Source or View Source command (available from the right-click menu in Google Chrome, Mozilla Firefox, or Internet Explorer). An even better way to explore, though, is to use the Inspect Element action from the right-click menu in those browsers. If you right-click on the item you want to learn more about, you’ll be able to see the HTML and the current CSS applied to the page.

I use Google Chrome most of the time, so I’ll show you Inspect Element screen in that browser. Here we’re looking at the button on CSS-Tricks.com:

2014-11-10 15_37_06-CSS-Tricks.png

You’ll see the HTML on the left side and the CSS on the right. You can check or uncheck different CSS rules, and you can double-click on things to edit them. Check out the right-click menus for even more options.

Sometimes you may need to click on a different element in order to see the CSS rules that are relevant to what you’re curious about. As you hover over different elements, you’ll see them highlighted on the page.

If you click on the Console tab, you can experiment with Javascript too. If you want to view both the inspect element information and the Javascript console at the same time, click on the icon that looks like a > on the right side. This is particularly handy if you have a large screen.

Hope that helps!

First steps towards Javascript testing

I know, I know, it’s about time I got the hang of this. Better late than never, right? =) Anyway, I spent some time going through tutorials for QUnit and Jasmine. For QUnit, I followed this Smashing Magazine tutorial on Javascript unit testing. I modified the code a little bit to add the Z timezone to the test data, since my tests initially didn’t pass.

test.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Refactored date examples</title>
    <link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.15.0.css" />
    <script src="http://code.jquery.com/qunit/qunit-1.15.0.js"></script>
    <script src="prettydate.js"></script>
    <script>
     test("prettydate.format", function() {
       function date(then, expected) {
         equal(prettyDate.format('2008/01/28 22:25:00Z', then), expected);
       }
       date("2008/01/28 22:24:30Z", "just now");
       date("2008/01/28 22:23:30Z", "1 minute ago");
       date("2008/01/28 21:23:30Z", "1 hour ago");
       date("2008/01/27 22:23:30Z", "Yesterday");
       date("2008/01/26 22:23:30Z", "2 days ago");
       date("2007/01/26 22:23:30Z", undefined);
     });
     function domtest(name, now, first, second) {
       test(name, function() {
         var links = document.getElementById('qunit-fixture').getElementsByTagName('a');
         equal(links[0].innerHTML, 'January 28th, 2008');
         equal(links[2].innerHTML, 'January 27th, 2008');
         prettyDate.update(now);
         equal(links[0].innerHTML, first);
         equal(links[2].innerHTML, second);
       });
     }

     domtest("prettyDate.update", '2008-01-28T22:25:00Z', '2 hours ago', 'Yesterday');
     domtest("prettyDate.update, one day later", '2008-01-29T22:25:00Z', 'Yesterday', '2 days ago');
    </script>
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture">
    <ul>
      <li class="entry" id="post57">
        <p>blah blah blah…</p>
        <small class="extra">
          Posted <span class="time"><a href="/2008/01/blah/57/" title="2008-01-28T20:24:17Z">January 28th, 2008</a></span>
          by <span class="author"><a href="/john/">John Resig</a></span>
        </small>
      </li>
      <li class="entry" id="post57">
        <p>blah blah blah…</p>
        <small class="extra">
          Posted <span class="time"><a href="/2008/01/blah/57/" title="2008-01-27T22:24:17Z">January 27th, 2008</a></span>
          by <span class="author"><a href="/john/">John Resig</a></span>
        </small>
      </li>
    </ul>
  </div>
</body>
</html>

For practice, I converted the QUnit tests to Jasmine. The first part of the test was easy, but I wanted a clean way to do the HTML fixture-based tests for prettydate.update too. Jasmine-JQuery gives you a handy way to have HTML fixtures. Here’s what my code ended up as:

spec/DateSpec.js

describe("PrettyDate.format", function() {
    function checkDate(name, then, expected) {
        it(name, function() {
            expect(prettyDate.format('2008/01/28 22:25:00Z', then)).toEqual(expected);
        });
    }
    checkDate("should display recent times", '2008/01/28 22:24:30Z', 'just now');
    checkDate("should display times within a minute", '2008/01/28 22:23:30Z', '1 minute ago');
    checkDate("should display times within an hour", '2008/01/28 21:23:30Z', '1 hour ago');
    checkDate("should display times within a day", '2008/01/27 22:23:30Z', 'Yesterday');
    checkDate("should display times within two days", '2008/01/26 22:23:30Z', '2 days ago');
});
describe("PrettyDate.update", function() {
    function domtest(name, now, first, second) {
       it(name, function() {
           loadFixtures('test_fixture.html');
           var links = document.getElementById('qunit-fixture').getElementsByTagName('a');
           expect(links[0].innerHTML).toEqual('January 28th, 2008');
           expect(links[2].innerHTML).toEqual('January 27th, 2008');
           prettyDate.update(now);
           expect(links[0].innerHTML).toEqual(first);
           expect(links[2].innerHTML).toEqual(second);
       });
    }
    domtest("prettyDate.update", '2008-01-28T22:25:00Z', '2 hours ago', 'Yesterday');
    domtest("prettyDate.update, one day later", '2008-01-29T22:25:00Z', 'Yesterday', '2 days ago');
});

jasmine.html

<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Jasmine Spec Runner v2.0.2</title>

  <link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.2/jasmine_favicon.png">
  <link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.2/jasmine.css">

  <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script type="text/javascript" src="lib/jasmine-2.0.2/jasmine.js"></script>
  <script type="text/javascript" src="lib/jasmine-2.0.2/jasmine-html.js"></script>
  <script type="text/javascript" src="lib/jasmine-2.0.2/boot.js"></script>
  <script type="text/javascript" src="jasmine-jquery.js"></script>

  <!-- include source files here... -->
  <script type="text/javascript" src="prettydate.js"></script>

  <!-- include spec files here... -->
  <script type="text/javascript" src="spec/DateSpec.js"></script>

</head>

<body>
</body>
</html>

I’m looking forward to learning how to use Jasmine to test Angular applications, since behaviour-driven testing seems to be common practice there. Little steps! =)

Emacs: Limiting Magit status to a directory

I’m probably using Git the wrong way. In addition to the nice neat repositories I have for various projects, I also sometimes have a big grab-bag repository that has random stuff in it, just so that I can locally version-control individual files without fussing about with Emacs’ numbered version systems. Sometimes I even remember to organize those files into directories.

When you have a Git repository that’s not one logical project but many little prototypes, using Magit status to work across the entire project can sometimes mean running into lots of distracting work in progress. I wanted a way to limit the scope of Magit status to a specific directory.

Here’s the experimental code I came up with:

      (defvar sacha/magit-limit-to-directory nil "Limit magit status to a specific directory.")
      (defun sacha/magit-status-in-directory (directory)
        "Displays magit status limited to DIRECTORY.
Uses the current `default-directory', or prompts for a directory
if called with a prefix argument. Sets `sacha/magit-limit-to-directory'
so that it's still active even after you stage a change. Very experimental."
        (interactive (list (expand-file-name
                            (if current-prefix-arg
                                (read-directory-name "Directory: ")
                              default-directory))))
        (setq sacha/magit-limit-to-directory directory)
        (magit-status directory))

      (defadvice magit-insert-untracked-files (around sacha activate)
        (if sacha/magit-limit-to-directory
            (magit-with-section (section untracked 'untracked "Untracked files:" t)
              (let ((files (cl-mapcan
                            (lambda (f)
                              (when (eq (aref f 0) ??) (list f)))
                            (magit-git-lines
                             "status" "--porcelain" "--" sacha/magit-limit-to-directory))))
                (if (not files)
                    (setq section nil)
                  (dolist (file files)
                    (setq file (magit-decode-git-path (substring file 3)))
                    (magit-with-section (section file file)
                      (insert "\t" file "\n")))
                  (insert "\n"))))
          ad-do-it))

      (defadvice magit-insert-unstaged-changes (around sacha activate)
        (if sacha/magit-limit-to-directory
            (let ((magit-current-diff-range (cons 'index 'working))
                  (magit-diff-options (copy-sequence magit-diff-options)))
              (magit-git-insert-section (unstaged "Unstaged changes:")
                  #'magit-wash-raw-diffs
                "diff-files"
                "--" sacha/magit-limit-to-directory
                ))
          ad-do-it))

      (defadvice magit-insert-staged-changes (around sacha activate)
        "Limit to `sacha/magit-limit-to-directory' if specified."
        (if sacha/magit-limit-to-directory
            (let ((no-commit (not (magit-git-success "log" "-1" "HEAD"))))
              (when (or no-commit (magit-anything-staged-p))
                (let ((magit-current-diff-range (cons "HEAD" 'index))
                      (base (if no-commit
                                (magit-git-string "mktree")
                              "HEAD"))
                      (magit-diff-options (append '("--cached") magit-diff-options)))
                  (magit-git-insert-section (staged "Staged changes:")
                      (apply-partially #'magit-wash-raw-diffs t)
                    "diff-index" "--cached" base "--" sacha/magit-limit-to-directory))))
          ad-do-it)))

Now I can bind C-x v C-d to sacha/magit-status-in-directory and get something that lets me focus on one directory tree at a time. You can see my config in context at http://sachachua.com/dotemacs#magit

It feels like I’m probably trying to do things the Wrong Way and I should probably just break things out into separate repositories. Even though I realized this early on, though, I ended up digging into how to implement it just for the sheer heck of seeing if Emacs would let me do it. =) I don’t know how often I’ll use this function, but it was a good excuse to learn more about the way Magit works.

It took me an hour to find my way around magit.el, but that’s more my fault than the code’s. At first I tried to override magit-diff-options, but I eventually remembered that the paths need to come at the end of the command line arguments. (I had a cold! My brain was fuzzy!) It was fun poking around, though. Looking forward to learning even more about Magit!

The Google Chrome extensions I use

Richard wanted to know which Google Chrome extensions I use. Here’s the list:

  • AdBlock: I still see ads, but I probably see fewer ads than before.
  • AngularJS Batarang: Great for debugging AngularJS applications.
  • Any.do Extension: I use this on my phone. Still thinking about how I can get something working with Org Mode and my phone. Might replace this with MobileOrg.
  • Application Launcher for Drive (by Google): I hardly use this, but it seems like a good idea.
  • Boomerang Calendar: Recognizes dates in e-mails and makes it easy to create appointments. Might not need it after Google improves its interface some more.
  • Boomerang for Gmail: Great for delaying replies, following up in case of non-response, or getting things to turn up in your inbox after a specified delay.
  • Capture Webpage Screenshot – FireShot: Can come in handy for full-page screenshots.
  • CSS Reloader: Handy during development.
  • Don’t track me Google: I use this mainly to remove the annoying Google redirection that happens when you copy links from search results without clicking through them. This way, I can copy and paste cleaner URLs.
  • Dragon Web Extension: Theoretically allows me to use speech recognition to control Chrome. I still haven’t gotten Dragon Naturally Speaking to be part of my workflow.
  • Evernote Web Clipper: Evernote is a great way to stash things I may want to refer to later.
  • Feedly: The extension lets me quickly subscribe to blogs. I prefer reading them on my phone, though.
  • Google Docs: Handy for sharing documents and editing them online.
  • Hangouts: I use this for video chats.
  • LastPass: Free Password Manager: Handy for storing and sharing passwords.
  • RescueTime for Chrome & ChromeOS: Tracks the sites I visit. I’m not doing anything with this data yet.
  • Rikaikun: Helps me learn Japanese when I hover over kanji.
  • RSS Subscription Extension (by Google): Displays a feed icon in the address bar if the site has alternate links to feeds. This way, I don’t have to hunt around for the right link.
  • Send from Gmail (by Google): Makes Gmail the default handler for e-mail addresses.
  • Tampermonkey: For injecting the Javascript that Skewer needs so that I can interact with webpages from Emacs. Could probably get away with using a bookmarklet instead. This tends to slow down Chrome, so I enable it only when I’m planning to develop.

What extensions do you use?