Neotree is a package for emacs (available for example on elpa) that displays the directory tree in a themeable tree-buffer. It looks nice but I was looking for a feature that I was missing. A window configuration I frequently use looks like this:

+-------+------------------+
|A      |B                 |  A - neotree
|       |                  |  B - some file
|       |                  |
|       |                  |
|       |                  |
+-------+------------------+

Now I am expecting that when I change the buffer in window B I have neotree in window A also show the buffers file. So I rolled up my sleeves and entered following lines of Emacs Lisp into my init.el:

  (defun mp:neotree-updater ()
    "Hook run on buffer list update."
    (interactive)
    (when (eq 2 (length (window-list)))
      (let* ((wnd-0 (nth 0 (window-list)))
             (wnd-1 (nth 1 (window-list)))
             (buf-0 (window-buffer wnd-0))
             (buf-1 (window-buffer wnd-1))
             (neo-buf nil)
             (other-buf nil)
             (filename nil))
        (when (or (eq buf-0 neo-global--buffer)
                  (eq buf-1 neo-global--buffer))
          (progn
            (if (eq buf-0 neo-global--buffer)
                (setq neo-buf buf-0
                      other-buf buf-0)
              (setq neo-buf buf-1
                    other-buf buf-0))
            (setq filename (buffer-file-name other-buf))
            (when filename
            (progn
              (when (file-exists-p filename)
                (message (concat "New filename " filename))
                (setq mp:neotree-go-to-dir filename)))))))))
 
  (add-hook 'buffer-list-update-hook 'mp:neotree-updater)
 
  (defun mp:neotree ()
    (interactive)
    (if mp:neotree-go-to-dir
        (progn
          (neotree-find mp:neotree-go-to-dir)
          (setq mp:neotree-go-to-dir nil))
      (neotree)))

Not perfect, but this way I can bind mp:neotree to „C-c n“ and have neotree jump to the current file when I hit „C-c n“. Since the mp:neotree-updater function is called in buffer-list-update-hook I was running into several recursions until I realized I can set buffer-list-update-hook temporarily to nil and so came up with this function:

(defun mp:neotree-updater ()
    (when (eq 2 (length (window-list)))
      (let* ((wnd-0 (nth 0 (window-list)))
             (wnd-1 (nth 1 (window-list)))
             (buf-0 (window-buffer wnd-0))
             (buf-1 (window-buffer wnd-1))
             (neo-buf nil)
             (other-buf nil)
             (neo-wnd nil)
             (other-wnd nil)
             (filename nil)
             (neo-buffer (get-buffer " *NeoTree*")))
        (when (and neo-buffer
                   (or (eq buf-0 neo-buffer)
                       (eq buf-1 neo-buffer)))
          (progn
            (if (eq buf-0 neo-buffer)
                (setq neo-buf buf-0
                      other-buf buf-1
                      neo-wnd wnd-0
                      other-wnd wnd-1)
              (setq neo-buf buf-1
                    other-buf buf-0
                    neo-wnd wnd-1
                    other-wnd wnd-0))
            (when (not (eq wnd-0 neo-wnd))
              (progn
                (setq filename (buffer-file-name other-buf))
                (when (and filename
                           (file-exists-p filename))
                  (progn
                    (let ((buffer-list-update-hook nil))
                      (neotree-find filename)
                      (select-window other-wnd)))))))))))

I have to take care for the case when I actually want to „C-x o“ into the neotree window, otherwise point will always jump out of the window with (select-window other-wnd).

Writing Java sourcecode in Emacs is a rather hard task. Emacs does not usually support the developer with lots of context awareness (friendly put…). What does the unsatisfied developer do when he is in need for functionality? He codes his own solution! So I have just started work on „Emacs Java Coding Extension (version 0.0.1)“. The project is admittedly in a very early phase. But there is an ambitious roadmap and some lines of code already available. Fresh from the scratch buffer where I tried it out:

(defvar mp:ac-classpath-cache nil)
 
(defun mp:ac-classpath-init ()
  (setq mp:ac-classpath-cache (mp:read-classes-from-jar)))
 
(defvar ac-source-classpath
  '((prefix . "^import \\(.*\\)")
    (init . mp:ac-classpath-init)
    (candidates . mp:ac-classpath-cache)))
 
(defun mp:read-classes-from-jar ()
  (with-temp-buffer
    (call-process "/usr/bin/unzip" nil t nil "-l" "/home/map/opt/jdk1.8.0_101/jre/lib/rt.jar")
    (goto-char (point-min))
    (let ((end 0)
          (result '())
          (classname ""))
      (while (search-forward ".class" nil t nil)
        (end-of-line)
        (setq end (point))
        (beginning-of-line)
        (goto-char (+ (point) 30))
        (setq classname (substring 
                         (replace-regexp-in-string "/" "."
                                                   (buffer-substring-no-properties (point) end))
                         0 -6))
        (setq result (cons classname result))
        (forward-line 1)
        (beginning-of-line))
      result)))

Put together correctly the code supplies a auto-complete source that knows about classes from the java rt.jar file (or any other jar file, or with some modifications several jar files).

Genisys is a Minecraft server written in PHP. It runs fine on Linux and forked from the Pocketmine codebase some time ago in the past. My attention came to Genisys after running Pocketmine for some time and constantly found myself in the situation, that after Minecraft Pocket Edition (which is my minecraft of choice) became updated Pocketmine did not allow the client to connect. Researching the topic in the Pocketmine forums revealed that there are a couple of people saying that Pocketmine is actually not further developed with enough manpower to keep on track with mcpe updates and that Genisys is more active developed. Since i did not know about Genisys and was not so happy with the disconnections I was facing I gave Genisys a try.

After installing Genisys and having ot up and running current clients could definetly connect to the server. That found out and beeing a developer on my own I want to do my part in sparing Genisys the fate of her „father“ project and at least start reading her source code so that maybe one day I can contribute to her development!

I share my experience here to easy the steps just in case someone is in the same situation like me: Here we go.

Getting Started

I just present some steps to get a private development environment.

Check out the source code

Genisys is available on Github under URL https://github.com/iTXTech/Genisys. So the first step is to clone the github repository:

$ git clone https://github.com/iTXTech/Genisys.git

The next step is get a php7 interpreter. Available here
To start the server cd into your genisys folder and execute the start script.

$ PHP_BINARY=/path/to/php7 ./start.sh

Php7 interpreters do not enjoy wide spread availability it seems. At least it is not available in the package repositories of my distribution of choice (Linux Mint Rosa). I managed to find a binary distribution but apparently lost the url… To see the server in action is quite fun since it works pretty nice. To proceed the development journey it’s a good idea to have some documentation at hand. Apparently the genisys github repository contains only a Doxygen file. This allows at least for creation of nice html formated source files.

Run doxygen

Doxygen creates a set of files that present the source code. To get it you need doxygen installed (I am on Mint Linux and had it already installed).

$ doxygen Doxyfile

Doxyfile resids in the Genisys root folder and hosts all the information necessary for doxygen to create a folder called „html“ filled with all the source-code in html format and more (like dependency trees for classes).

Start reading some source code

This is the tricky part and for me currently work in progress. Beeing a minecraft player i found it convincing to start with what i see when i play and find the classes that seem responsible/involved in the source code. So to stay i started my browsing the source-code journey with the namespaces:

  • block
  • item
  • entity

My current impression goes like this: Block involves all the stuff that is not moving (Air, Dirt, Door, Fence, Wine, Water) normally. Entity on the other hand involves moving members of the world (Monsters, Rabbits, Humans, etc). And last the item namespace involves all the stuff that can be picked up and overlaps with the block namespace (for example there is a potato in both namespaces…).

I know there is not much to take with from here but as i noted it is work in progress!

Official Sites

There is an online version of the Genisys doxygen site: https://storage.googleapis.com/itx-technologies-141911.appspot.com/docs/genisys/index.html and since Genisys sourcecode is hosted on github there is a list of issues available: https://github.com/iTXTech/Genisys/issues

Introduction

I actually do Web-development in my private life. Smaller projects for myself like a „homepage“ (Is this term still used?) or for „the kids“ – to bring them in contact with the web, web technologies and all that. My work-flow is „overlookable“ and projects normally involve

  • a HTML file
  • a CSS file
  • a Javascript file

I have done this for quiet some time and normally used barebone emacs to open a new file, fill in some content, arrange window/buffer layout, open a new file and fill in some more content. Escpecially with those smaller „projects“ I normally ended up with a layout like this:

Buffer Layout For Web Projects

At some point in time I realized that emacs can support me here and I did:

 

(defcustom web-project-root "~/public_html/" "New web projects are stored in this directory." :group 'web)
 
(defun mp/start-web-project (name)
  "Create a new web project with NAME.  Create initial html, js, css file."
  (interactive "MProjectname? ")
  (let ((projectroot (concat web-project-root name)))
    (unless (file-exists-p projectroot)
      (mkdir projectroot))
    (select-frame (make-frame))
    (split-window-vertically)
    (find-file (concat projectroot "/" name ".html"))
    (save-buffer)
    (other-window 1)
    (find-file (concat projectroot "/" name ".js"))
    (save-buffer)
    (split-window-horizontally)
    (find-file (concat projectroot "/" name ".css"))
    (other-window -1)
    (copy-file "~/.emacs.d/templates/jquery-3.0.0.js" (concat projectroot "/"))
    (switch-to-buffer (concat name ".html"))
    (mp/html-project-post-processing name)))

(mp/html-project-post-processing name) fills in page title and css template filename:

(defun mp/html-project-post-processing (name)
  "This method looks for strings %CSSFILE% and %TITLE% and replaces them with some meaningful values."
  (save-excursion
    (goto-char (point-min))
    (when (re-search-forward "%TITLE%" nil t)
      (replace-match name 'fixedcase))
    (goto-char (point-min))   
    (when (re-search-forward "%NAME%" nil t)
      replace-match name 'fixedcase))
    (goto-char (point-min))
    (when (re-search-forward "%CSSFILE%" nil t)
      (replace-match (replace-regexp-in-string (regexp-quote ".html") ".css" (buffer-name) 'fixedcase 'literal) 'fixedcase))))

To start a new project I can now (mp/start-web-project) and have my preferred buffer/window layout and templates filled into the empty buffers! Also emacs creates a directory in web-project-root, which is ~/public_html/ for me so that apache finds the newly created project. It saves me a lot of time and I am really happy with it!

Templates

I do have a template for Javascript and Html. There’s not much in it but I do feel more comfortable when I do not look at empty buffers 🙂

HTML Template

My html template fills in some bare-bone html5 content and takes care for indentation. There are also a couple of javascript files included.

(define-auto-insert '("\\.html\\'" . "HTML5 Skeleton")
  [ '(nil
      "<!DOCTYPE html>\n"
      "<html>\n"
      "<head>\n"
      "<meta charset=\"UTF-8\">\n"
      "<title>%TITLE%</title>\n"
      "<script src=\"jquery-3.0.0.js\"></script>\n"
      "<script src=\"subrx.js\"></script>\n"
      "<script src=\"%NAME%.js\"></script>\n"
      "<link rel=\"stylesheet\" type=\"text.css\" href=\"%CSSFILE%\">\n"
      "</head>\n"
      "<body>\n"
      "</body>\n"
      "</html>\n"
      ) indent-buffer ] )

The indent-buffer function is used to indent the whole buffer, once the skelton is inserted into the buffer:

(defun indent-buffer ()
  (interactive)
  (indent-region (point-min) (point-max)) )

Javascript Template

(define-auto-insert '("\\.js\\'" . "Javscript Skeleton")
  [ '(nil
    "/*\n * "
    (file-name-nondirectory (buffer-file-name)) "\n"
    " * Started on " (format-time-string "%A, %e %B %Y.") \n
    " */" \n \n \n ) indent-buffer ] )

Sometimes when I write a little python script – with only a few lines of code – it starts growing and I keep adding functionality. When a certain threshold is reached I start thinking that there should be a logger used (instead of print) and maybe a configuration file (instead of all these commandline switches). Since python coding is not something I do on a daily basis python code is not something I come up with just like that. So I either copy & paste code from other scripts or even have to look up how exactly the logger is set up, how a configuration file is loaded or how signal handler is registered. It’s always the same story and as a keen Emacs user I finally made it an end 🙂
Using emacs auto-insert-mode. In my configuration auto-insert-mode inserts the file „template.py“ from my „~/.emacs.d/templates/“ directory and inserts into the buffer whenever I open a yet non-existing file with the .py extension:

(setq auto-insert-directory "~/.emacs.d/templates/"
      auto-insert-query nil)
(add-to-list 'auto-insert-alist '(".*\\.py[3]?$" . [ "template.py" ]))

This works pretty well and of course template.py hosts my nitty gritty python boiler plate that I want to see in my scripts (no matter how small they are 🙂 ):

#!/usr/bin/python3
 
import logging
import logging.handlers
import signal
import sys
import os
import time
import argparse
 
# Author     : Matthias
# Description: Python script template
 
class Application:
 
    name               = ''
    version            = ''
    log                = None
    properties         = None
    parser             = None
    args               = None
 
    def __init__(self):
        signal.signal(signal.SIGINT, Application.signal_int_handler)        
        parser = argparse.ArgumentParser(description="", epilog="")
        parser.add_argument("-v", "--verbose", help="Be more verbose when logging", action="store_true")
        parser.add_argument("-P", "--properties", help="A properties file for use by the application", type=str)
        parser.add_argument("-l", "--loghost", help="Name of host to receive log messages", default="127.0.0.1")
        parser.add_argument("-p", "--logport", help="Port of service to receive log messages", type=int, default=logging.handlers.DEFAULT_TCP_LOGGING_PORT)
        parser.add_argument("-d", "--logdomain", help="Domain for logging", default="this-script")
        parser.add_argument("-r", "--remotelog", help="Enable remote logging with default host and port", action="store_true")
        self.args = parser.parse_args()
        self.parser = parser
        self.setup_logging()
        self.read_properties(self.args.properties)
 
    def setup_logging(self):
        self.log = logging.getLogger(self.args.logdomain)
        rootlogger = logging.getLogger()
        formatstring='%(asctime)s %(levelname)-15s %(name)s # %(message)s'
        formatter = logging.Formatter(fmt=formatstring, datefmt='%d.%m.%y %I:%M:%S')
        handler = None
        if self.args.remotelog:
            handler = logging.handlers.SocketHandler(self.loghost_name, self.loghost_port)
        else:
            handler = logging.StreamHandler(sys.stderr)
        handler.setFormatter(formatter)
        rootlogger.addHandler(handler)
        level = logging.INFO
        if self.args.verbose:
            level = logging.DEBUG
        self.log.setLevel(level)
        rootlogger.setLevel(level)
        self.log.propagate=1
 
    def read_properties(self, filename):
        """ Read the file passed as parameter as a properties file. """
        if filename:
            properties = {}
            comment_char = "#"
            seperator = ":"
            with open(filename, "rt") as f:
                for line in f:
                    l = line.strip()
                    if l and not l.startswith(comment_char):
                        key_value = l.split(seperator)
                        key = key_value[0].strip()
                        value = seperator.join(key_value[1:]).strip().strip('"') 
                        properties[key] = value 
            self.properties = properties
 
    @staticmethod
    def signal_int_handler(signal, frame):
        interrupt_msg = '\r\n\r\n{} {} terminated by keyboard interrupt'.format(Application.name, Application.version)
        print(interrupt_msg)
        exit(0)
 
    def run(self):
        pass
 
def main():
    app = Application()
    app.log.info('{} {} is starting'.format(app.name, app.version))
    app.run()
    app.log.info('{} {} is done'.format(app.name, app.version))
 
if __name__ == '__main__':
    main()
 
#
# Done
#
# # # end of script

Beeing busy with a lot of things it’s hard to find time to cultivate the essential programming skills. I managed to find some time and did some Javascript coding (once again…). The result is here: click. This site helps you train basic arithmetic (numbers between 0 and 100). Good for primary school 2nd grade. Exercises are picked on the vertical right sidebar. Exercises populate a table and can then be solved in any order. Have fun.