Skip to content

Latest commit

 

History

History
3725 lines (2686 loc) · 103 KB

Emacs.org

File metadata and controls

3725 lines (2686 loc) · 103 KB

Emacs From Scratch Configuration

PROPERTIES:

Lexical binding to top of file

-*- lexical-binding: t -*-

Tangle and Reload init file

(org-babel-tangle)
(load-file "~/.emacs.d/init.el")

Collect Usage Stats

(setq use-package-compute-statistics t)

Treesitter auto mode

Links:

(use-package treesit-auto
  :custom
  (treesit-auto-install 'prompt)
  :config
  (treesit-auto-add-to-auto-mode-alist 'all)
  (global-treesit-auto-mode))

Termux Issue

(setq cg/is-termux
      (string-suffix-p "Android" (string-trim (shell-command-to-string "uname -a"))))

;; Fix an issue accessing the ELPA archive in Termux
(when cg/is-termux
  (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3"))

Eearly Init - not needed?

https://www.masteringemacs.org/article/whats-new-in-emacs-27-1

However, if your init file changes the values of

  • package-load-list
  • or ‘package-user-dir’, or sets
  • package-enable-at-startup to nil then
  • You can move that code to the early init file (see above), so those settings apply before Emacs tries to activate the packages.
  • You can use the new ‘package-quickstart’ so activation of packages does not need to pay attention to ‘package-load-list’ or ‘package-user-dir’ any more.

The whole Init File

Configure Startup

;; The default is 800 kilobytes.  Measured in bytes.
;; (setq gc-cons-threshold (* 50 1000 1000))
;; (setq gc-cons-threshold (* 350 1000 1000))

;; Profile emacs startup
(add-hook 'emacs-startup-hook
          (lambda ()
            (message "*** Emacs loaded in %s with %d garbage collections."
                     (format "%.2f seconds"
                             (float-time
                              (time-subtract after-init-time before-init-time)))
                     gcs-done)))

Coding System

(prefer-coding-system 'utf-8)
(set-default-coding-systems 'utf-8)
(set-language-environment 'utf-8)
(set-selection-coding-system 'utf-8)

Package and Load Process / Function Paths

;; Setup packages
;; code obsolete in emacs27
(if (version< emacs-version "27.1")
    (package-initialize)
  )

(add-to-list 'load-path (expand-file-name "doom-snippets" user-emacs-directory))
(setq doom-snippets-enable-short-helpers nil)
(add-to-list 'load-path "~/.emacs.d/el")
;; (add-to-list 'load-path "~/.emacs.d/elpa/s-20210616.619/")
;; (require 's)

(use-package s :ensure t)

;; This is already the default. why set it again
(setq user-emacs-directory "~/.emacs.d/")
;; Functions (load all files in defuns-dir)
;;(add-to-list 'load-path user-emacs-directory)
(setq defuns-dir (expand-file-name "defuns" user-emacs-directory))
(dolist (file (directory-files defuns-dir t "^[^.#].*el$"))
  (when (file-regular-p file)
    (load (file-name-sans-extension file))))

;;  (require 'title-time)
;; (require 'setup-daimler-proxy)
;; ;; No splash screen please ... jeez
(setq inhibit-startup-message t)

;; Settings for currently logged in user
;; keep automatic customizations separately
(setq custom-file "~/.emacs.d/custom.el")
(load custom-file 'noerror)

;; create user customization directory for specific username/hostname combination
(defvar user-settings-dir)
(setq user-settings-dir
      (joindirs user-emacs-directory "users" (concat user-login-name "-" (system-name) )))

(mkdir user-settings-dir t)
(add-to-list 'load-path user-settings-dir)

;; load all settings from user machine combination
(when (file-exists-p user-settings-dir)
  (mapc 'load (directory-files user-settings-dir nil "^[^.#].*el$")))

;; Write backup files to own directory
(setq backup-directory-alist
      `(("." . ,(expand-file-name "backups" user-emacs-directory))))

;; Make backups of files, even when they're in version control
(setq vc-make-backup-files t)

;; Save point position between sessions
(require 'saveplace)
(setq-default save-place t)
(setq save-place-file (expand-file-name ".places" user-emacs-directory))

;; Setup elnode before packages to stop it from starting a server
;;(require 'setup-elnode)
;; Setup packages
(require 'setup-package)
;; Set path to dependencies
(setq site-lisp-dir
      (expand-file-name "site-lisp" user-emacs-directory))

;; Set up load path and
(add-to-list 'load-path site-lisp-dir)

;; Add external projects to load path
(dolist (project (directory-files site-lisp-dir t "\\w+"))
  (when (file-directory-p project)
    (add-to-list 'load-path project)))
Straight
Try to install straigt to ~/.config/emacs

https://emacs.stackexchange.com/questions/60507/change-location-for-straight-el-working-directories

(message straight-base-dir) (defvar config-list) (setq config-list (directory-files (joindirs (getenv “HOME”) “.config” “emacs” emacs-version “straight”))) (seq-filter (lambda (x) (string-match “emacs” x)) config-list) (cl-remove-if-not #’evenp ‘(1 2 3 4 5))

(directory-files (joindirs (getenv “HOME”) “.config” “emacs” emacs-version “straight”)

(setq straight-base-dir (joindirs (getenv "HOME") ".config" "emacs" emacs-version))
(mkdir straight-base-dir t)
Initial bootstrap

First, place the following bootstrap code in your init-file:

  (defvar bootstrap-version)
  (let ((bootstrap-file
         (expand-file-name
          "straight/repos/straight.el/bootstrap.el"
          (or (bound-and-true-p straight-base-dir)
              user-emacs-directory)))
        (bootstrap-version 7))
    (unless (file-exists-p bootstrap-file)
      (with-current-buffer
          (url-retrieve-synchronously
           "https://raw.githubusercontent.com/radian-software/straight.el/develop/install.el"
           'silent 'inhibit-cookies)
        (goto-char (point-max))
        (eval-print-last-sexp)))
    (load bootstrap-file nil 'nomessage))

(straight-use-package 'use-package)
(straight-use-package 'yasnippet)
  • This should only run once, so it can be left in the init file
  • it wil create the directory straight in .emacs.d
  • To install a package: (straight-use-package ‘evil)
  • M-x straight-use-package to see list of installables
  ;; org-20210929
  ;; org-contrib-0.6
  ;; org-ml-20230410.30
  ;; org-sql-20240819.2145
  ;; org-roam-20240715.1750
  ;; org-chef-20231127.1601
  ;; org-tree-slide-20230826.1234
  ;; org-special-block-extras-20230721.43
  ;; calfw-org-20170411.220
(use-package org :straight (:type built-in))
(use-package org-contrib :straight t)
(use-package org-ml :straight t)
(use-package org-sql :straight t)
(use-package org-roam :straight t)
(use-package org-tree-slide :straight t)
(use-package org-special-block-extras :straight t)
(use-package calfw-org :straight t)
(use-package yasnippet-classic-snippets :straight t)

;; (use-package org :straight t)
Defaults
;; Allow pasting selection outside of Emacs
(setq x-select-enable-clipboard t)
(setq x-select-enable-primary t)

;; Auto refresh buffers
(global-auto-revert-mode 1)

;; Also auto refresh dired, but be quiet about it
(setq global-auto-revert-non-file-buffers t)
(setq auto-revert-verbose nil)

;; Show keystrokes in progress
(setq echo-keystrokes 0.1)

;; Set to t in order to move files to trash when deleting
(setq delete-by-moving-to-trash nil)

;; Real emacs knights don't use shift to mark things
(setq shift-select-mode nil)

;; Transparently open compressed files
(auto-compression-mode t)

;; Enable syntax highlighting for older Emacsen that have it off
(global-font-lock-mode t)

;; Answering just 'y' or 'n' will do
(defalias 'yes-or-no-p 'y-or-n-p)

;; UTF-8 please
(setq locale-coding-system 'utf-8) ; pretty
(set-terminal-coding-system 'utf-8) ; pretty
(set-keyboard-coding-system 'utf-8) ; pretty
(set-selection-coding-system 'utf-8) ; please
(prefer-coding-system 'utf-8) ; with sugar on top

;; Frame titles which are short and informative
(setq frame-title-format '("%b - Emacs"))

;; Show active region
(transient-mark-mode 1)
(make-variable-buffer-local 'transient-mark-mode)
(put 'transient-mark-mode 'permanent-local t)
(setq-default transient-mark-mode t)

;; Remove text in active region if inserting text
(delete-selection-mode 1)

;; ;; Don't highlight matches with jump-char - it's distracting
;; (setq jump-char-lazy-highlight-face nil)

;; Always display line and column numbers
(setq line-number-mode t)
(setq column-number-mode t)

;; Lines should be 80 characters wide, not 72
(setq fill-column 80)

;; Save a list of recent files visited. (open recent file with C-x f)
(recentf-mode 1)
(setq recentf-max-saved-items 100) ;; just 20 is too recent

;; Highlight matching parentheses when the point is on them.
(show-paren-mode 1)

;; Undo/redo window configuration with C-c <left>/<right>
(winner-mode 1)

;; Never insert tabs
(setq-default indent-tabs-mode nil)

;; Show me empty lines after buffer end
(setq-default indicate-empty-lines t)

;; Easily navigate sillycased words
(global-subword-mode 1)

;; ;; Don't break lines for me, please
;; (setq-default truncate-lines t)

;; Keep cursor away from edges when scrolling up/down
;; (require 'smooth-scrolling)
;; (setq scroll-step 1)
;; (setq scroll-conservatively 10000)
(setq auto-window-vscroll nil)

;; org-mode: Don't ruin S-arrow to switch windows please (use M-+ and M-- instead to toggle)
(setq org-replace-disputed-keys t)

;; Fontify org-mode code blocks
(setq org-src-fontify-natively t)


;; ;; Sentences do not need double spaces to end. Period.
;; (set-default 'sentence-end-double-space nil)

;; Add parts of each file's directory to the buffer name if not unique
(require 'uniquify)
(setq uniquify-buffer-name-style 'forward)

;; A saner ediff
(setq ediff-diff-options "-w")
(setq ediff-split-window-function 'split-window-horizontally)
(setq ediff-window-setup-function 'ediff-setup-windows-plain)

;; Nic says eval-expression-print-level needs to be set to nil (turned off) so
;; that you can always see what's happening.
(setq eval-expression-print-level nil)

;; When popping the mark, continue popping until the cursor actually moves
;; Also, if the last command was a copy - skip past all the expand-region cruft.
(defadvice pop-to-mark-command (around ensure-new-position activate)
  (let ((p (point)))
    (when (eq last-command 'save-region-or-current-line)
      ad-do-it
      ad-do-it
      ad-do-it)
    (dotimes (i 10)
      (when (= p (point)) ad-do-it))))

;; don't try to raise windows when switching to a buffer, because this
;; fails in any sane tiling window manager
(setq ido-default-file-method 'selected-window
      ido-default-buffer-method 'selected-window)

;; highlight the current line in all buffers
(global-hl-line-mode 1)

(setq  realgud-safe-mode nil)
Show Line Numbers per Default, with some Exceptions
(global-display-line-numbers-mode t)

;; Override some modes which derive from the above
(dolist (mode '(term-mode-hook
                ag-mode-hook
                magit-mode-hook
                dired-mode-hook
                comint-mode-hook
                shell-mode-hook
                helm-mode-hook
                ibuffer-mode-hook
                eshell-mode-hook))

  (add-hook mode (lambda () (display-line-numbers-mode 0)))
  )
Set frame transparency, maximize windows.
(set-frame-parameter (selected-frame) 'alpha '(99 . 99))
(add-to-list 'default-frame-alist '(alpha . (99 . 99)))
(set-frame-parameter (selected-frame) 'fullscreen 'maximized)
(add-to-list 'default-frame-alist '(fullscreen . maximized))
Interface more minimalsitic(menubar etc.))

Disable visible scrollbar when in graphical display see https://superuser.com/questions/313398/how-to-prevent-the-symbols-function-definition-is-void-error-when-running-em

(if (display-graphic-p)
    (progn
      (tool-bar-mode t)
      (scroll-bar-mode -1)
      (set-fringe-mode 10)        ; Give some breathing room
      ))

This does not result in visible menubar

(defun restore-menu-bar()
  (interactive)
  (if (fboundp 'scroll-bar-mode) (scroll-bar-mode 1))
  (if (fboundp 'tool-bar-mode) (tool-bar-mode 1))
  (if (fboundp 'menu-bar-mode) (menu-bar-mode 1)))

(restore-menu-bar)
(tool-bar-mode 1)          ; Disable the toolbar
;;  (tooltip-mode -1)           ; Disable tooltips

(menu-bar-mode t)            ; Disable the menu bar
Keyboard Interaction (and the Evil Chapter)
;; Smart M-x is smart - der ido fuer M-x
(require 'smex)
(smex-initialize)

;; Setup key bindings
(require 'key-bindings)
(require 'setup-helm)

;; Diminish modeline clutter
(require 'diminish)
Expand region

;; expand regions semantically ;; see https://github.com/magnars/expand-region.el

(use-package expand-region
  :bind ("C-=" . er/expand-region))
Undo system
  • C-r in evil/vim: undo/redo functionality
  • it will suggest to customize the evil undo system, see customization below
  • Evil has some fine tunings of the undo system: (setq evil-want-fine-undo t), see here.
;; Represent undo-history as an actual tree (visualize with C-x u)
;; (setq undo-tree-mode-lighter "")
;;(setq undo-tree-mode-lighter "Undo-Tree") defaul

;;(setq evil-want-fine-undo t)
(require 'undo-tree)
(global-undo-tree-mode)
Undo tree create “*.~undo-tree~” files

Apparently the default has changed recently, so we need to set the history for the time being, see this reddit post.

(setq undo-tree-auto-save-history nil)

The post also suggests that emacs-undo-fu-session might be interesting.

Evil

https://github.com/noctuid/evil-guide https://nathantypanski.com/blog/2014-08-03-a-vim-like-emacs-config.html https://www.linode.com/docs/guides/emacs-evil-mode/

Evil-magit is not part of the Evil Collection.

evil-emacs-state-modes: which modes come up in emacs mode

;; do ot apply yet
(defun cg/evil-hook ()
  (dolist (mode '(custom-mode
                  eshell-mode
                  shell-mode
                  term-mode
                  ibuffer-mode
                  ag-mode
                  dired-mode
                  flycheck-mode
                  python-ts-mode
                  python-mode
                  ))
    (add-to-list 'evil-emacs-state-modes mode)
    ))

(use-package evil
  :init
  (setq evil-want-integration t)  ;; seems to be always good
  (setq evil-want-keybinding nil) ;; david wilson prefers not to use thes3
  (setq evil-want-C-u-scroll nil) ;; do not override C-u prefix
  (setq evil-want-C-i-jump nil)
  (setq evil-undo-system 'undo-tree) ;; alternative is undo-fu
  ;; :hook
  :config
  ;; evil: green: normal mode;
  (evil-mode 1)
  ;; drop back to normal mode using C-g
  (define-key evil-insert-state-map (kbd "C-g") 'evil-normal-state)
  ;; in vim insert mode, C-h is now backspace. Normally in emacs it would enter help
  (define-key evil-insert-state-map (kbd "C-h") 'evil-delete-backward-char-and-join)
  :hook (evil-mode . cg/evil-hook)
  )

;;  (evil-set-initial-state 'messages-buffer-mode 'normal)
;;  (evil-set-initial-state 'dashboard-mode 'normal))

(use-package evil-collection
  :after evil
  :config
  (evil-collection-init))

Evil Nerd Commenter

M-; does comment, but the behavior sometimes isn’t exactly what you’d expect.

https://github.com/redguardtoo/evil-nerd-commenter

(use-package evil-nerd-commenter
  :ensure t
  :bind ("M-/" . evilnc-comment-or-uncomment-lines))
Usage and Vim bindingsStatesNormal State

evil-normal-state CTRL-z: go to emacs state when in normal state White dot

Emacs state CTRL-z: go back to normal state when in emacs state evil-emacs-state Blue dotInsert State

evil-insert-state i insert here I Insert at the beginning of the line a cursor at end A go into insert mode at end of line o with newline O Delete Line and go into insert s substitute under cursor S Similar to O? etc.

asdasdasddddddddddddddddddddasd sdasdasdasdasdasdasdasdasda asdasdasdasdasdasdasdadsasdsadas

Paste in insert state

see https://stackoverflow.com/questions/2861627/paste-in-insert-mode While in insert mode hit CTRL-R {register}

Examples:

CTRL-R * will insert in the contents of the clipboard CTRL-R ” (the unnamed register) inserts the last delete or yank. To find this in vim’s help type :h i_ctrl-r

Visual state

evil-visual-state

C-v Visual Block S-v Visual Line v Visual State

v$ - select until end of line v^ - select until beginning of line

vip - select paragraph

Replace State

Enter Replace state from normal state typing R Overwrites text under cursor

Evil Motion State

M-x evil motion state golded dot

Evil Operator-Pending

M-x evil operator-state No clue what this does

Normal mode and bindingsVisual Mode
  • S-v: Switch to visual mode
Navigating
  • ^: got to beginning of line
  • j: next line
  • k: previous line
  • b: back one word
  • w: forward one word
  • C-u up half a page -> not working for me: Why: bound to “universal arument” in emacs
  • C-d down half a page
  • ) to the first word of the next sentence
  • ( to the previous sentence
  • u undo thing
  • G to to last line
  • gg to to first line
  • 2w navigate two words forward

w - until the start of the next word, EXCLUDING its first character. e - to the end of the current word, INCLUDING the last character. $ - to the end of the line, INCLUDING the last character. 0 - Got to the beginning of the line

asssss asdas s asdasda dasd

Indenting

The == re-indents the line to suit its new position. For the visual-mode mappings, gv reselects the last visual block = re-indents that block.

Moving Lines around

:m .-2 move line one up :m .+1 move line one down

The same in vimscript that goes to .vimrc:

nnoremap <A-j> :m .+1<CR>== nnoremap <A-k> :m .-2<CR>==

https://github.com/emacs-evil/evil-collection

Deleting

d motion

d - is the delete operator. motion - is what the operator will operate on (listed below).

  • dd delete line
  • dw delete

w - until the start of the next word, EXCLUDING its first character. e - to the end of the current word, INCLUDING the last character. $ - to the end of the line, INCLUDING the last character. ^ - to the beginning of the line b - back to the beginning of the word { - delete to beginning of paragraph } - delete to end of paragraph

d3w - delete three words in the future d5d - delete 5 lines 2dd - delete 2 lines 2dd - delete 2 lines

y3w - copy the next three words

das a hier is sowas wie ein modiefier des delete word commands:

daw - delete a word and all whitespace around it. a stands for around diw - Delete just the word: das i ist für inside? dw - ??? dap - delete around paragraph 5dap - delete around 5 paragraphs di( - delete inside paremtheses di{ - delete inside curly bracces di” seems not to work!

asdasd {a abn asdasd asd asdfgg } noch asdasd (asdasdasd )

dd - delete (cut) a line dw - delete the word right of the cursor d$ - delete from cursor to the end of the line d^ - delete from cursor to beginning of line

asssssssssssssssssssssssssssssssssssssssss

D - delete (cut) to the end of the line

Replace Modifier

c is the change modifier

caw - replace current word ciw - replace inside word c$ - change from cursor to end of line C - same as c$

Type rx to replace the character at the cursor with x .

asdasd (asd asdas asd)

Cutting and pasting

y - yank (copy) marked text d - delete marked text

yy - yank (copy) a line 2yy - yank (copy) 2 lines yiw - yank (copy) word under the cursor

yip - copy current paragraph

Searching and Replacing

https://vim.fandom.com/wiki/Search_and_replace#Basic_search_and_replace

:s/foo/bar/g Find each occurrence of ‘foo’ (in the current line only), and replace it with ‘bar’.

:%s/foo/bar/g Find each occurrence of ‘foo’ (in all lines), and replace it with ‘bar’.

:%s/foo/bar/gc Change each ‘foo’ to ‘bar’, but ask for confirmation first.

n - next occ N - prev occ

Typing / followed by a phrase searches FORWARD for the phrase. Typing ? followed by a phrase searches BACKWARD for the phrase. CTRL-O takes you back to older positions, CTRL-I to newer positions.

To substitute new for the first old in a line type :s/old/new To substitute new for all ‘old’s on a line type :s/old/new/g To substitute phrases between two line #’s type :#,#s/old/new/g To substitute all occurrences in the file type :%s/old/new/g To ask for confirmation each time add ‘c’ :%s/old/new/gc

Upercasing and lower casing

See the following methods:

~ : Changes the case of current character guu : Change current line from upper to lower. gUU : Change current LINE from lower to upper. guw : Change to end of current WORD from upper to lower. guaw : Change all of current WORD to lower. gUw : Change to end of current WORD from lower to upper. gUaw : Change all of current WORD to upper. g~~ : Invert case to entire line g~w : Invert case to current WORD guG : Change to lowercase until the end of document. gU) : Change until end of sentence to upper case gu} : Change to end of paragraph to lower case gU5j : Change 5 lines below to upper case gu3k : Change 3 lines above to lower case

source: https://stackoverflow.com/questions/2946051/changing-case-in-vim#:~:text=2%20Answers&text=Visual%20select%20the%20text%2C%20then,gu%20for%20lowercase.

Close whole editor

ZQ - closes whole editor

More stuff in normal mode:
  • zz: put current line under cursor in the middle
  • zt: put current line under cursor at the top
  • zb: put current line to the bottom
  • { : Move by paragraph up
  • } : Move by paragraph down
  • % show matching ({[

löetasdasdjlajdklsadjklaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaas

Windwos Buffers SplitsWorking with buffers

:bd - delete buffer C-6 - goto the previous buffer

Working with windows

:split - split horizontally :vsplit - split left/right :sort - sort lines

Working with Tabs

Ctrl+WT (that’s a capital T) to move any open window to its own tab. :tabnew - create a tab :tabnext

:tabfind filename opens file in new tab :tabclose close current tab

Working with splits

Switching between visible buffers

ctrl-w w or ctrl-w crtl-w

Close the current window, each window at a time:

Control+w q

maximize” the current split:

Ctrl-w _

Make the current window the only one:

:on :only CTRL-w CTRL-o And yes, also CTRL-W o has the same effect (as Nathan answered).

Now to open a new split and open the bar file inside it:

:sp bar

split again and open the cat file:

:sp cat

Increase current split by 5 lines

Ctrl-w 5+<

And to return to equalized splits:

Ctrl-w =

To split the current split again, only vertically (and at the same time open the file named “dog”) run:

:vsp dog

CommandAction
:sp filenameOpen filename in horizontal split
:vsp filenameOpen filename in vertical split
Ctrl-w h Ctrl-w ←Shift focus to split on left of current
Ctrl-w l Ctrl-w →Shift focus to split on right of current
Ctrl-w j Ctrl-w ↓Shift focus to split below the current
Ctrl-w k Ctrl-w ↑Shift focus to split above the current
Ctrl-w n+Increase size of current split by n lines
Ctrl-w n-Decrease size of current split by n lines
Open files

:e ~/.bashrc - edit this file :r /path/to/file - inserts file into current buffer

https://blog.confirm.ch/mastering-vim-opening-files/

Links

/home/audeering.local/cgeng/code/data_collection/aisoundlab/portal/src/app/app-init.ts

Programming
Programming General
(require 'realgud)
(require 'setup-projectile)
;; (eval-after-load 'ido '(require 'setup-ido)) ;; interactive break M-x
;; Setup lsp mode prior to setup-java
;; setup for lsp and dap
(require 'setup-auto-complete)
Rainbow Delim
(use-package rainbow-delimiters
  :hook (prog-mode . rainbow-delimiters-mode)
  )

;; Rainbow Delimiters ;;(setup (:pkg rainbow-delimiters) ;; (:hook-into prog-mode))

Notebooks

(require ‘ein) (require ‘ein-notebook) (require ‘ein-subpackages)

OR

https://github.com/nnicandro/emacs-jupyter#kernelnotebook-server

M-x jupyter-kernel-list-servers M-x jupyter-connect-server-repl

(dired ”jpy:localhost#8890:”) (dired “http:localhost#8890:”)

(dired ”jpy:localhost#8890:”)

LSP General
Install
(require 'setup-lsp)
UsageMore Interface Options

(setq lsp-ui-doc-enable t) (setq lsp-ui-doc-enable t) (setq lsp-ui-peek-enable t) (setq lsp-ui-sideline-enable t) (setq lsp-ui-imenu-enable t) (setq lsp-ui-flycheck-enable t)

Comments and Notesoften it is necessary to delete ~/.emacs.d/.lsp-session-v1Reinstallation:

see https://emacs-lsp.github.io/lsp-mode/page/installation/:

M-x package-install RET lsp-mode RET

AND:

  1. Delete your LSP-related packages
  2. Restart Emacs
  3. Install the new versions of the packages.
Deactivtate jdee for java files
;; (require 'setup-java)
;; deactivate  jdee for  loading java files
(setq auto-mode-alist
      (append '(("\\.java\\'" . java-mode)) auto-mode-alist))
Debugging: Setup dap mode (including python)
;; run dap mode setup
(require 'setup-dap-mode)
Python Info
pyenv

https://github.com/pythonic-emacs/pyenv-mode https://github.com/pyenv/pyenv

(pyenv-mode) then run pyenv-mode-set

Launching DAP

These are sitting in REPLS and Debugging in python.org

Linting, Checkers, Static Code Analysis - Hooks

Overview about formatting, organizing imports and style checkers:

Usefuly Hooks Article: https://enzuru.medium.com/helpful-emacs-python-mode-hooks-especially-for-type-hinting-c4b70b9b2216

LintingLinters overview ;; pylint: .pylintrc

pip install –upgrade pylint pip install –upgrade flake8

pylint

https://liuluheng.github.io/wiki/public_html/Python/flycheck-pylint-emacs-with-python.html

Pyright Code Checking Information Django Problem ;; microsoft/pyright#1359 ;; Django Stubs: https://pypi.org/project/django-stubs/

;; flycheck ;; using pyright in emacs lsp as well as in vscode gives identical errors except ;; false errors in emacs that are flagged as “lsp-flycheck-info-unnecessary” ;; emacs-lsp/lsp-mode#2255

;; Vergleich der standard-Autoformatters: ;; https://www.kevinpeters.net/auto-formatters-for-python

;; Emacs LSP-Ansatz: ;; jede Sprache macht es selbst, also kein allgemeines setup für lsp und dap: ;; https://alpha2phi.medium.com/emacs-lsp-and-dap-7c1786282324

;; Format Imports Isort - ;; formatting using black and isort ;; https://cereblanco.medium.com/setup-black-and-isort-in-vscode-514804590bf9

;; autoflake will also remove unused imports using pyflakes (which is what flake8 uses to check for extra imports ;; flycheck-pyflakes 20170330.2311 available melpa Support pyflakes in flyc ;; pip install autoflake ;; importmagic ;; ;; yapf stanza example for setup.cfg ;; ;; ;; [yapf] ;; based_on_style = pep8 ;; spaces_before_comment = 4 ;; split_before_logical_operator = true ;; line-length = 119

;; lisp function to auto-remove unused imports: ;; https://gist.github.com/kracekumar/77d29c7410199fd2cda4

;; linting ;; https://code.visualstudio.com/docs/python/linting ;; emacs-lsp/lsp-mode#1327

ImportMagic

Importmagic does not work!

https://github.com/anachronic/importmagic.el $ pip install importmagic epc

;;(use-package importmagic
 ;;   :ensure t
    ;; will add the hook into python usepackage configuration
    ;;:config
    ;;(add-hook 'python-mode-hook 'importmagic-mode)
   ;; )
Type Hinting ;; https://stackoverflow.com/questions/44094494/can-pycharm-suggest-or-autocomplete-or-insert-type-hints/44102211#44102211Code Coverage in Emacs
;;  cov                            20210330.44    available    melpa    Show coverage stats in the fringe.
;;  coverage                       20191113.1958  available    melpa    Code coverage line highlighting
;;  coverlay                       20190414.940   available    melpa    Test coverage overlays
LSP Python: Writing setup-python.el file the conf
Header
;;; setup-python.el --- summary -*- lexical-binding: t -*-
;;
;;; Code:
Function to restart workspace - not functional

see http://ergoemacs.org/emacs/elisp_file_name_dir_name.html

(defun lsp-workspace-restart-deep ()
  (interactive
   (delete-file (joindirs user-emacs-directory  ".lsp-session-v1"))
   (lsp-workspace-restart))
  )

(load-file “~/.emacs.d/init.el”)

Running Tests with python-pytest

https://github.com/wbolster/emacs-python-pytest

(use-package python-pytest
  :ensure t
  )
(setq python-pytest-confirm t)

Hydra Usage:

M-x python-pytest-dispatch
Format buffer using yapf

really neceessary as yapf-mode, yapfify etc. exist

see https://github.com/seagle0128/.emacs.d/blob/master/lisp/init-lsp.el

(defun cg/python-yapf-format-buffer ()
  (interactive)
  (when (and (executable-find "yapf") buffer-file-name)
    (call-process "yapf" nil nil nil "-i" buffer-file-name)))

;; add hook example
;; (add-hook 'python-mode-hook
;;           (lambda ()
;;             (add-hook 'after-save-hook #'lsp-python-ms-format-buffer t t)))

Function to remove unused imports using autoflake
;; does not work as custom variable
;; (defcustom python-autoflake-path
;;   (replace-regexp-in-string "\n$" "" (shell-command-to-string "which autoflake"))
;;   )

(defvar python-autoflake-path
  (replace-regexp-in-string "\n$" "" (shell-command-to-string "which autoflake"))
  )

(defun python-remove-unused-imports()
  "Use Autoflake to remove unused function"
  "autoflake --remove-all-unused-imports -i unused_imports.py"
  (interactive)
  (shell-command
   (format "%s --remove-all-unused-imports -i %s"
           python-autoflake-path
           (shell-quote-argument (buffer-file-name))))
  (revert-buffer t t t))
Function to remove unused variables using autoflake
  • this goes by using the –remove-unused-variables flag
(defun python-remove-unused-variables()
  "Use Autoflake to remove unused function"
  "autoflake --remove-all-unused-imports -i unused_imports.py"
  (interactive)
  (shell-command
   (format "%s --remove-unused-variables -i %s"
           python-autoflake-path
           (shell-quote-argument (buffer-file-name))))
  (revert-buffer t t t))
Configure black formatter for brunette
  • blacken-buffer will format the buffer
  • customizations are better kept in pyproject.toml when using black itself,
  • setup.cfg is interpreted by black
(use-package use-package-ensure-system-package :ensure t)
(use-package blacken
  ;; :ensure t
  ;; :ensure-system-package (black . "pip3 install black")
  :custom
  (blacken-executable "brunette")
  ;; (blacken-line-length 119)
  )
LinksFormatting providers in vscode

https://dev.to/adamlombard/how-to-use-the-black-python-code-formatter-in-vscode-3lo0

Aggregate Function to clean up - not functioning
(defun python-cleanup-this-file ()
  "All cleaning actions run in chain..."
  (interactive)
  (blacken-buffer)
  (python-remove-unused-imports)
  (py-isort-buffer)
  (python-remove-unused-imports)
  )
Rst autocomplete

This packages seems not to be really well maintained. I am revoming it as of 2024-08-21

https://github.com/tkf/auto-complete-rst

;; auto-complete-rst
(require 'auto-complete-rst)
(auto-complete-rst-init)
;; specify other sources to use in rst-mode
(setq auto-complete-rst-other-sources
      '(ac-source-filename
        ac-source-abbrev
        ac-source-dictionary
        ac-source-yasnippet))
flymake ruff
(use-package flymake-ruff
  :ensure t
  :hook
  (python-mode . flymake-ruff-load)
  (python-ts-mode . flymake-ruff-load)
  )
defconst line width - still needed?
(defconst python-linewidth 89)
coverage
(require 'pycoverage)
(defun my-coverage ()
  (interactive)
  (when (derived-mode-p 'python-mode)
    (progn
      (pycoverage-mode))))
pyvenv - virtual environments
(use-package pyvenv
  :config
  (pyvenv-mode 1)
  (pyvenv-tracking-mode 1)
  )
Flyckeck Attempt to use Pylint

https://www.flycheck.org/en/28/_downloads/flycheck.html#Configuring-checkers https://stackoverflow.com/questions/37720869/emacs-how-do-i-set-flycheck-to-python-3

;; (add-hook 'flycheck-mode-hook #'flycheck-virtualenv-setup)
(defun flycheck-python-setup ()
  (flycheck-mode)
  )
;; (add-hook 'python-mode-hook #'flycheck-python-setup)
(org-babel-tangle)
(load-file "~/.emacs.d/init.el")
python-lsp-server specific

https://emacs-lsp.github.io/lsp-mode/page/lsp-pylsp/ https://github.com/python-lsp/python-lsp-server emacs-lsp/lsp-mode#2777 https://vxlabs.com/2018/06/08/python-language-server-with-emacs-and-lsp-mode/

pip install ‘python-lsp-server[all]’ pip install ‘python-lsp-server[websockets]

rope Pyflakes McCabe pycodestyle pydocstyle autopep8 yapf flake8 pylint

(use-package lsp-mode
  :ensure t
  :config

  ;; make sure we have lsp-imenu everywhere we have LSP
  (require 'lsp-imenu)
  (add-hook 'lsp-after-open-hook 'lsp-enable-imenu)
  ;; get lsp-python-enable defined
  ;; NB: use either projectile-project-root or ffip-get-project-root-directory
  ;;     or any other function that can be used to find the root directory of a project
  (lsp-define-stdio-client lsp-python "python"
                           #'projectile-project-root
                           '("pyls"))

  ;; make sure this is activated when python-mode is activated
  ;; lsp-python-enable is created by macro above
  (add-hook 'python-mode-hook
            (lambda ()
              (lsp-python-enable)))

  ;; lsp extras
  (use-package lsp-ui
    :ensure t
    :config
    (setq lsp-ui-sideline-ignore-duplicate t)
    (add-hook 'lsp-mode-hook 'lsp-ui-mode))

  (use-package company-lsp
    :config
    (push 'company-lsp company-backends))

  ;; NB: only required if you prefer flake8 instead of the default
  ;; send pyls config via lsp-after-initialize-hook -- harmless for
  ;; other servers due to pyls key, but would prefer only sending this
  ;; when pyls gets initialised (:initialize function in
  ;; lsp-define-stdio-client is invoked too early (before server
  ;; start)) -- cpbotha
  (defun lsp-set-cfg ()
    (let ((lsp-cfg `(:pyls (:configurationSources ("flake8")))))
      ;; TODO: check lsp--cur-workspace here to decide per server / project
      (lsp--set-configuration lsp-cfg)))

  (add-hook 'lsp-after-initialize-hook 'lsp-set-cfg))

  ;; (require 'lsp-pylsp)
Pyright specific codeThe configuration

https://emacs-lsp.github.io/lsp-pyright/

Note: lsp-python-ms might be loaded with precedence and should be UNINSTALLED in orde to get this working!

Should become :tangle no when removed.

(use-package python-mode
  :straight t
  :hook (python-mode . (lambda ()
                         (require 'lsp-pyright)
                         (require 'highlight-indent-guides)
                         (require 'sphinx-doc)
                         (sphinx-doc-mode t)
                         (highlight-indent-guides-mode -1)
                         (auto-fill-mode)
                         (flycheck-python-setup)
                         (set-fill-column python-linewidth)
                         ;;(highlight-indent-guides-mode)
                         ;; (importmagic-mode)
                         (lsp-deferred)
                         ;; (yapf-mode)
                         (lsp-treemacs)
                         )
                     )
  :custom
  ;; NOTE: Set these if Python 3 is called "python3" on your system!
  ;; (python-shell-interpreter "python3")
  ;; (dap-python-executable "python3")
  ;; should be .dir-local:
  ;; (lsp-pyright-venv-path "~/.venvs/py37")
  (dap-python-debugger 'debugpy)
  :config
  (require 'dap-python)
  ;; (setq lsp-pyright-server-cmd `("node" "~/.vscode/extensions/ms-python.vscode-pylance-2021.5.3/dist/pyright.bundle.js" "--stdio"))
  )


(setq lsp-enable-file-watchers nil)
(setq lsp-file-watch-threshold 2000)

(setq lsp-pyright-auto-import-completions t)
;;  Determines whether pyright automatically adds common search paths.
;; i.e: Paths like "src" if there are no execution environments defined in the
;; config file.
(setq lsp-pyright-auto-search-paths t)
(setq lsp-pyright-log-level "trace")

(require 'dap-python)

;; (lsp-client-settings)

(use-package company
  :after lsp-mode
  :hook (lsp-mode . company-mode)
  ;; :bind (:map company-active-map
  ;;        ("<tab>" . company-complete-selection))
  ;;       (:map lsp-mode-map
  ;;        ("<tab>" . company-indent-or-complete-common))
  :custom
  (company-minimum-prefix-length 1)
  (company-idle-delay 0.0))

(use-package company-box
  :hook (company-mode . company-box-mode))
Additional NotesPyright and npm

Problem:

npx pyright
node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)

nvm install 16.15.1 nvm use 16.15.1

npx pyright wird nur zum diagnostizieren genommen. was man will ist pyright von der console zu starten

Build Pyright

Pylance = Pyright + IntelliCode AI models (not open-source)

https://github.com/emacs-lsp/lsp-mode/issues/1863:
entweder über vs code installieren oder selbst bauen
git clone https://github.com/microsoft/pyright
cd pyright
npm i
npm run build:serverProd
   ;; das sorgt dafür dass pyright bei mir im Pfad ist
   ;; which pyright
   ;; momentan befindet sich das hier: /home/audeering.local/cgeng/.nvm/versions/node/v12.22.1/bin/pyright
Use VS Code Version
;; Nutzung der VSCode Version:
;; (setq lsp-pyright-server-cmd `("node" "~/.vscode/extensions/ms-python.vscode-pylance-2021.5.3/dist/pyright.bundle.js" "--stdio"))
;; (setq lsp-pyright-server-cmd `("node" "~/pyright/client/server/server.bundle.js" "--stdio"))

Activating venvs: After changing the virtual env, the lsp workspace has to be restarted: see emacs-lsp/lsp-pyright#7

(lsp-restart-workspace)
Configuration
  • Pyright LS uses a file called pyrightconfig.json to include settings

This is documented at https://github.com/microsoft/pyright/blob/main/docs/configuration.md

code/data_collection/aisoundlab/audb_covid_19/1.0.0/

pyrightconfig.json example

Not sure whehter emacs interprets this at all

{
    "exclude": ["**/node_modules", "**/__pycache__"],
    "ignore": ["**/node_modules", "**/__pycache__"],
    "include": ["flextensor", "tvm","1.0.0"],
    "pythonPlatform": "Linux",
    "pythonVersion": "3.7",
    "reportMissingImports": true,
    "reportMissingTypeStubs": false,
    "stubPath": "typings",
    "typeCheckingMode": "basic",
    "venvPath": "/home/audeering.local/cgeng/.venvs",
    "venv": "py37"
}

*****

shell interpreter

Needs to come BELOW the (use-package python-mode ...) configuration:

(setq python-shell-interpreter "ipython3"
        python-shell-interpreter-args "-i --simple-prompt")
Footer for setup-python
(provide 'setup-python)

;;; setup-python-lsp-python ends here
;; not  lsp
;; (require 'setup-python-elpy-jedi)   ;; was the old setup-python.el
;; (require 'setup-python-lsp-emacs-from-scratch)
;; (require 'setup-python-pyright)
;; (require 'setup-python-lsp-pyright)
(require 'setup-python)
LSP SQL

https://github.com/lighttiger2505/sqls

(add-hook 'sql-mode-hook 'lsp)
(setq lsp-sqls-workspace-config-path nil)
(setq lsp-sqls-connections
    '(
      ((driver . "sqlite3") (dataSourceName . "/home/audeering.local/cgeng/work/myfiles/bikerides/data/processed/db.sqlite3"))
      ;; ((driver . "mysql") (dataSourceName . "yyoncho:local@tcp(localhost:3306)/foo"))
      ;; ((driver . "mssql") (dataSourceName . "Server=localhost;Database=sammy;User Id=yyoncho;Password=hunter2;"))
      ;; ((driver . "postgresql") (dataSourceName . "host=127.0.0.1 port=5432 user=yyoncho password=local dbname=sammy sslmode=disable"))
      )
    )
Other LSP Languages
(require 'setup-typescript)
(require 'setup-angular)
;; currently broken:
;; (require 'setup-c-lsp-clangd)
;; (require 'setup-c++)
;; (require 'setup-python-lsp-remember-you)

(eval-after-load 'whitespace '(require 'setup-whitespace))
(eval-after-load 'tramp '(require 'setup-tramp))
;; (require 'setup-perspective)
;; (require 'setup-ffip)
;; (require 'setup-paredit)

(require 'mmm-auto)
(mmm-add-mode-ext-class 'html-mode "\\.php\\'" 'html-php)

(require 'setup-js2-mode)
(require 'setup-web-mode)
(require 'mmm-auto)
(require 'setup-web-mode)
(require 'setup-vue-mode)
R using ess

https://confunguido.github.io/blog/20190317_emacs_for_R.html https://github.com/sejdemyr/.emacs.d/blob/master/init.el

(require 'setup-ess)
    ;;; setup-ess.el --- summary -*- lexical-binding: t -*-
  ;;
    ;;; Code:

;;; emacs speaks statistics
  (use-package ess
    :ensure t
    :init
    (require 'ess-site)
    )

  (provide 'setup-ess)
  ;;; setup-ess ends here

Electric Pair Mode
;; see http://ergoemacs.org/emacs/emacs_insert_brackets_by_pair.html
(electric-pair-mode 1)

>***** SQL code formatting

see https://github.com/purcell/sqlformat

(setq sqlformat-command 'sqlformat)
(setq sqlformat-args nil)

;; (setq sqlformat-command 'pgformatter)
;; (setq sqlformat-args '("-s2" "-g"))
Json Files
  ;;; setup-json-mode.el --- summary -*- lexical-binding: t -*-

;; Author: CGeng
;; Maintainer: CGeng
;; Version: version
;; Package-Requires: (dependencies)

;;; Commentary:

;; commentary

;;; Code:


  ;;; name.el ends here
(add-hook 'json-mode-hook
          (lambda ()
            (make-local-variable 'js-indent-level)
            (setq js-indent-level 4)
            (flycheck-mode)
            )
          )


(defun beautify-json ()
"Make json formatting beautiful in selected region.
    Formats json region to be better readable by a human."
  (interactive)
  (let ((b (if mark-active (min (point) (mark)) (point-min)))
        (e (if mark-active (max (point) (mark)) (point-max))))
    (shell-command-on-region b e
                             "python -m json.tool" (current-buffer) t)))


(provide 'setup-json-mode)
;;; setup-json-mode.el ends here
Org-Mode
org-roam

(use-package org-roam :ensure t)

Is compiler there? Should be non-nil:

(executable-find “cc”)

cgeng@ap-cgeng:~/.emacs.d/elpa/emacsql-sqlite-20221127.2146/sqlite$ ls -tl total 8968 -rw-r–r– 1 cgeng domain users 613416 Dez 1 20:47 sqlite3.h -rw-r–r– 1 cgeng domain users 5070 Dez 1 20:47 emacsql.c -rw-r–r– 1 cgeng domain users 472 Dez 1 20:47 Makefile Meine erste ideemeine zweite Idee-rw-r–r– 1 cgeng domain users 8549001 Dez 1 20:47 sqlite3.c

https://emacs.stackexchange.com/questions/56064/cannot-enable-org-roam-mode-no-emacsql-sqlite-binary-avaiable

(org-roam find executable sqlite3)

make emacsql-sqlite

(use-package org-roam
  :straight t
  :init
  (setq org-roam-v2-ack t)
  :custom
  (org-roam-directory "~/RoamNotes")
  (org-roam-completion-everywhere t)
  :bind (("C-c n l" . org-roam-buffer-toggle)
         ("C-c n f" . org-roam-node-find)
         ("C-c n i" . org-roam-node-insert)
         :map org-mode-map
         ("C-M-i" . completion-at-point)
         :map org-roam-dailies-map
         ("Y" . org-roam-dailies-capture-yesterday)
         ("T" . org-roam-dailies-capture-tomorrow))
  :bind-keymap
  ("C-c n d" . org-roam-dailies-map)
  :config
  (require 'org-roam-dailies) ;; Ensure the keymap is available
  (org-roam-db-autosync-mode))
Getting Started with Org Roam - Build a Second Brain in Emacs*

https://www.youtube.com/watch?v=AyhPmypHDEw https://systemcrafters.cc/build-a-second-brain-in-emacs/getting-started-with-org-roam/

  • org-roam-node-find create the node
  • org roam node insert Link to other node:
  • org-roam-buffer-toggle
Capturing notes efficiently

https://www.youtube.com/watch?v=YxgA5z2R08I&t=0s https://systemcrafters.net/build-a-second-brain-in-emacs/capturing-notes-efficiently/

Org Roam: The Best Way to Keep a Journal in Emacs

https://www.youtube.com/watch?v=3-sLBaJAtew&t=0s https://systemcrafters.net/build-a-second-brain-in-emacs/keep-a-journal/

System Crafters Live! - Can You Apply Zettelkasten in Emacs?

https://www.youtube.com/watch?v=-TpWahIzueg https://systemcrafters.net/live-streams/august-06-2021/

Video von Sönke Ahrens: https://www.youtube.com/watch?v=JnS3g68zCXw

Setting requiring main entry Point

==(load “org-capture-templates-slim”)= wird in setup-org geladen. Dort wird die Browser Extension dann konfiguriert.

Default Values:

  • selected template: p
  • unselected template: L

My Values:

  • selected template: op
  • unselected template: oL
(require 'setup-org) ;; organizer todo notes etc
Setting up org-general
Main Blob
;; Enable org-mode
(require 'org)

;; For encrypting files
(require 'org-crypt)

;; For template expansion
;; https://www.reddit.com/r/orgmode/comments/7jedp0/easy_templates_expansion_not_working/
(require 'org-tempo)

;; Remove trailing whitespace
(add-hook 'org-mode-hook
          (lambda ()
            (add-to-list 'write-file-functions 'delete-trailing-whitespace)))

;; Enable intelligent text wrapping
(add-hook 'org-mode-hook
          (lambda ()
            (visual-line-mode)
            (adaptive-wrap-prefix-mode)))

;; Prevent extra spaces from showing up after headings
(setq org-cycle-separator-lines 0)

;; Enable syntax-highlighting
(setq org-src-fontify-natively t)

;;;; Export Options

;; Disable subscripts on export
(setq org-export-with-sub-superscripts nil)

;; Disable table of contents on export
(setq org-export-with-toc nil)

;; Export drawers
;; (setq org-export-with-drawers t)

;; Export to clipboard to paste in other programs
(defun my/org-export-region-html ()
  "Export region to HTML, and copy it to the clipboard."
  (interactive)
  (save-window-excursion
    (let* ((buf (org-export-to-buffer 'html "*Formatted Copy*" nil t nil t))
           (html (with-current-buffer buf (buffer-string))))
      (with-current-buffer buf
        (shell-command-on-region
         (point-min)
         (point-max)
         "clip"))
      (kill-buffer buf))))

;; Shortcuts
;; (global-set-key "\C-cl" 'org-store-link)
(global-set-key "\C-ca" 'org-agenda)
(global-set-key "\C-cc" 'org-capture)
(define-key org-mode-map "\C-cv" 'org-reveal)
(define-key org-mode-map "\C-cn" 'org-next-link)
(define-key org-mode-map "\C-cp" 'org-property-action)

;; Property inheritance
(setq org-use-property-inheritance nil)

;; Tag inheritance
(setq org-use-tag-inheritance nil)

;; Use global IDs
(require 'org-id)
(setq org-id-link-to-org-use-id t)

;; Update ID file .org-id-locations on startup
(org-id-update-id-locations)

;; Add ID properties to all headlines in the current file which do not already have one
(defun my/org-add-ids-to-headlines-in-file ()
  (interactive)
  (org-map-entries 'org-id-get-create))

;; Uncomment to enable writing IDs to all org entries before saving
;; (add-hook 'org-mode-hook
;;  (lambda ()
;;    (add-hook 'before-save-hook 'my/org-add-ids-to-headlines-in-file nil 'local)))


;; Org-refile

;; Targets include this file and any file contributing to the agenda - up to 9 levels deep
(setq org-refile-targets '((org-agenda-files :maxlevel . 9)))
(setq org-refile-use-outline-path 'file)
(setq org-outline-path-complete-in-steps nil)
(setq org-refile-allow-creating-parent-nodes t)

;; Add previous heading to refile note automatically
(defun my/org-refile-with-note-parent-link ()
  "Wrapper for `org-refile' which automatically adds the previous
parent org-link to the note in the form \"From [[id:hash][Heading]].\"

Requires `org-log-refile' to be set to 'note."
  (interactive)
  ;; (if (equal current-prefix-arg '(4))
  ;;    (org-refile)
    (save-excursion
      (let ((start-level (funcall outline-level)))
        (if (<= start-level 1)
            ;; Remember that org-make-link-string exists
            (push (list (buffer-file-name)
                        (file-name-nondirectory (buffer-file-name)))
                  org-stored-links)
          (progn
            (outline-up-heading 1 t)
            (call-interactively 'org-store-link)))))
    (org-refile)
    (with-simulated-input "RET RET"
      (org-insert-link))
    (insert ".")
    (beginning-of-line nil)
    (insert "From ")
    (org-ctrl-c-ctrl-c))

(define-key org-mode-map "\C-c\C-w" 'my/org-refile-with-note-parent-link)

;; ;; Has not been implemented for org-agenda-mode-map
;; (define-key org-agenda-mode-map "\C-c\C-w" 'my/org-refile-with-note-parent-link)

(defun my/org-copy-outline-path ()
  "Function to copy outline path of current org-item (agenda or file) to clipboard."
  (interactive)
  (let ((m (org-get-at-bol 'org-marker)))
    (kill-new (replace-regexp-in-string "//" "/" (org-with-point-at m (org-display-outline-path t t "/" nil))))))

(define-key org-mode-map "\C-co" 'my/org-copy-outline-path)

;; Collapse plain lists
(setq org-cycle-include-plain-lists 'integrate)

;; Change and freeze time
(defun my/freeze-time (&optional freeze-time-time)
  "Freeze `current-time' at the current active or inactive timestamp. If point
is not on a timestamp, the function prompts for one. If time is not specified,
either by the timstamp under point or prompt, the time defaults to the
current HH:MM of today at the selected date."
  (interactive)
  (let ((time
         (cond
          ((if (boundp 'freeze-time-time)
               freeze-time-time))
          ((if (org-at-timestamp-p 'lax) t)
           (match-string 0))
          (t
           (org-read-date t nil nil "Input freeze time:")))))
    (eval (macroexpand
           `(defadvice current-time (around freeze activate)
              (setq ad-return-value ',
                    (append (org-read-date nil t time) '(0 0))))))
    (set-face-background 'fringe "firebrick2")))

(global-set-key "\C-cf" 'my/freeze-time)

;; Release changed / frozen time
(defun my/release-time ()
  "Release the time frozen by `freeze-time'."
  (interactive)
  (if (advice--p (advice--symbol-function 'current-time))
      (progn
        (ad-remove-advice 'current-time 'around 'freeze)
        (ad-activate 'current-time)
        (set-face-background 'fringe nil))
    (message "Time is not currently frozen")))

(global-set-key "\C-cr" 'my/release-time)

;; Change time-stamp increments to 1 minute
(setq org-time-stamp-rounding-minutes '(0 1))

;; Re-define org-switch-to-buffer-other-window to NOT use org-no-popups.
;; Primarily for compatibility with shackle.
(defun org-switch-to-buffer-other-window (args)
  "Switch to buffer in a second window on the current frame.
In particular, do not allow pop-up frames.
Returns the newly created buffer.

Redefined to allow pop-up windows."
  ;;  (org-no-popups
  ;;     (apply 'switch-to-buffer-other-window args)))
  (switch-to-buffer-other-window args))

;; Org-toggle-latex-fragment options

;; Make text bigger
(setq org-format-latex-options (plist-put org-format-latex-options :scale 1.5))

;; Semi-center equations by moving number to the right using [leqno]
(setq org-format-latex-header "\\documentclass[reqno]{article}
\\usepackage[usenames]{color}
[PACKAGES]
[DEFAULT-PACKAGES]
\\pagestyle{empty}             % do not remove
% The settings below are copied from fullpage.sty
\\setlength{\\textwidth}{\\paperwidth}
\\addtolength{\\textwidth}{-3cm}
\\setlength{\\oddsidemargin}{1.5cm}
\\addtolength{\\oddsidemargin}{-2.54cm}
\\setlength{\\evensidemargin}{\\oddsidemargin}
\\setlength{\\textheight}{\\paperheight}
\\addtolength{\\textheight}{-\\headheight}
\\addtolength{\\textheight}{-\\headsep}
\\addtolength{\\textheight}{-\\footskip}
\\addtolength{\\textheight}{-3cm}
\\setlength{\\topmargin}{1.5cm}
\\addtolength{\\topmargin}{-2.54cm}")

;; Go to the next indented paragraph when currently in a bulleted list.
(defun my/org-next-paragraph ()
  (interactive)
  (move-end-of-line nil)
  (org-return)
  (org-return)
  (org-return)
  (indent-for-tab-command nil)
  (org-cycle nil)
  (org-self-insert-command 1)
  (beginning-of-visual-line 1)
  (previous-line 1 1)
  (delete-forward-char 1 nil)
  (end-of-visual-line 1)
  (org-delete-backward-char 1))

(define-key org-mode-map "\C-ci" 'my/org-next-paragraph)

;; Add note on property change
(add-to-list 'org-log-note-headings
             '(property . "Property %-12s from %-12S %t"))

(defcustom my/org-property-ignored-properties
  '("ID" "LAST_REPEAT" "Via" "ARCHIVE_TIME" "ARCHIVE_FILE" "ARCHIVE_OLPATH" "ARCHIVE_CATEGORY" "ARCHIVE_TODO" "Effort" "EFFORT" "NOTER_DOCUMENT" "NOTER_PAGE")
  "List of properties to exclude from my/org-property-change-note."
  :group 'org
  :type 'list)

(defun my/org-property-store-previous-val (property)
  "Store previous property value prior to modifying it with `org-property-action'."
  (setq my/org-property-previous-val
        (org-entry-get nil property)))

(advice-add #'org-read-property-value :before #'my/org-property-store-previous-val)

(defun my/org-property-change-note (prop val)
;;   "Add property changes to the logbook. Requires modifying `org-add-log-note'
;; to include:

;; ((eq org-log-note-purpose 'property)
;;  (format \"\\\"%s\\\" property change from \\\"%s\\\"\"
;;          (or org-log-note-state \"\")
;;          (or org-log-note-previous-state \"\")))

;; or replacing the entire cond block with:

;; (cond
;;  ((member org-log-note-purpose (mapcar 'car org-log-note-headings))
;;   \"changing property\")
;;  (t (error \"This should not happen\")))

;; and byte compiling org.el."
  (message (concat "Changing " prop " from " val))
  (if (not 'my/org-property-previous-val)
      (if (not (member prop my/org-property-ignored-properties))
      (org-add-log-setup 'property prop my/org-property-previous-val))))

;; In the interim, I've just re-defined the function
(defun org-add-log-note (&optional _purpose)
  "Pop up a window for taking a note, and add this note later."
  (remove-hook 'post-command-hook 'org-add-log-note)
  (setq org-log-note-window-configuration (current-window-configuration))
  (delete-other-windows)
  (move-marker org-log-note-return-to (point))
  (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  (goto-char org-log-note-marker)
  (org-switch-to-buffer-other-window "*Org Note*")
  (erase-buffer)
  (if (memq org-log-note-how '(time state))
      (org-store-log-note)
    (let ((org-inhibit-startup t)) (org-mode))
    (insert (format "# Insert note for %s.
# Finish with C-c C-c, or cancel with C-c C-k.\n\n"
                    (cond
                     ((eq org-log-note-purpose 'clock-out) "stopped clock")
                     ((eq org-log-note-purpose 'done)  "closed todo item")
                     ((eq org-log-note-purpose 'state)
                      (format "state change from \"%s\" to \"%s\""
                              (or org-log-note-previous-state "")
                              (or org-log-note-state "")))
                     ((eq org-log-note-purpose 'reschedule)
                      "rescheduling")
                     ((eq org-log-note-purpose 'delschedule)
                      "no longer scheduled")
                     ((eq org-log-note-purpose 'redeadline)
                      "changing deadline")
                     ((eq org-log-note-purpose 'deldeadline)
                      "removing deadline")
                     ((eq org-log-note-purpose 'refile)
                      "refiling")
                     ((eq org-log-note-purpose 'note)
                      "this entry")
                     ((eq org-log-note-purpose 'property)
                      (format "\"%s\" property change from \"%s\""
                              (or org-log-note-state "")
                              (or org-log-note-previous-state "")))
                     (t (error "This should not happen")))))
    (when org-log-note-extra (insert org-log-note-extra))
    (setq-local org-finish-function 'org-store-log-note)
    (run-hooks 'org-log-buffer-setup-hook)))

(add-hook 'org-property-changed-functions 'my/org-property-change-note)

(defun my/org-link-copy (&optional arg)
  "Copy the entire org-link (link and description) at point and put it on the killring.
With prefix C-u, just copy the org-link link."
  (interactive "P")
  (when (org-in-regexp org-bracket-link-regexp 1)
    (if (null arg)
        (let ((link (match-string-no-properties 0)))
          (kill-new link)
          (message "Copied link: %s" link))
      (let ((link (org-link-unescape (match-string-no-properties 1))))
        (kill-new link)
        (message "Copied link: %s" link)))))

(define-key org-mode-map "\C-ch" 'my/org-link-copy)

;; Add ability to move forward by timestamp
(setq my/org-timestamp-search-failed nil)

;; Note: Need to advise org-context since exiting the logbook doesn't collapse it.
(defun my/org-next-timestamp (&optional search-backward)
  "Move forward to the next timestamp.
If the timestamp is in hidden text, expose it."
  (interactive "P")
  (when (and my/org-timestamp-search-failed (eq this-command last-command))
    (goto-char (point-min))
    (message "Timestamp search wrapped back to beginning of buffer"))
  (setq my/org-timestamp-search-failed nil)
  (let* ((pos (point))
         (ct (org-context))
         (a (assq :timestamp ct))
         (srch-fun (if search-backward 're-search-backward 're-search-forward)))
    (cond (a (goto-char (nth (if search-backward 1 2) a)))
          ((looking-at org-element--timestamp-regexp)
           ;; Don't stay stuck at timestamp without an org-link face
           (forward-char (if search-backward -1 1))))
    (if (funcall srch-fun org-element--timestamp-regexp nil t)
        (progn
          (goto-char (match-beginning 0))
          (when (org-invisible-p) (org-show-context)))
      (goto-char pos)
      (setq my/org-timestamp-search-failed t)
      (message "No further timestamps found"))))

(define-key org-mode-map "\C-ct" 'my/org-next-timestamp)

(defun my/org-timestamp-convert-dirty-regexp-hack ()
  "Convert all org-mode timestamps in buffer from the
form <2019-01-04 08:00-10:00> to <2019-01-04 08:00>--<2019-01-04 10:00>"
  (interactive)
  (goto-char (point-min))
  (while (re-search-forward "<\\([0-9- A-z]\\{15\\}\\)\\([0-9]\\{2\\}:[0-9]\\{2\\}\\)-\\([0-9]\\{2\\}:[0-9]\\{2\\}\\)>" nil t)
    (replace-match "<\\1\\2>--<\\1\\3>" t nil)))

;; Have dired store org-link when a file or files(s) are renamed
(defun my/dired-rename-file (file newname ok-if-already-exists)
  "Store org-link to the renamed file."
  (push (list newname (file-name-nondirectory newname)) org-stored-links))

(advice-add #'dired-rename-file :after #'my/dired-rename-file)

;; Org-mode Priorities
;; Default highest is 65 (A)
;; Default default is 66 (B)
;; Default lowest is 65 (C)
;; Default should be "C" - two levels of priority should be enough
(setq org-default-priority 67)

;; Insert Capture Template At End of Current
(defun my/org-capture-after-current ()
  (interactive)
  (org-insert-heading-after-current)
  (kill-line -1)
  (org-return)
  (delete-forward-char 1)
  ;; This doesn't work for some reason
  ;; (let ((current-prefix-arg (digit-argument 0)))
  ;;   (call-interactively #'org-capture)))
  (execute-kbd-macro (read-kbd-macro "C-u 0 C-c c")))

(defun my/org-backup-files ()
  "Create backup of entire org-mode directory in the archive directory. I really need to start
using git for this instead."
  (interactive)
  (let* ((date-time (format-time-string "%Y-%m-%d %H.%M.%S"))
         (org-backup-directory
          (concat (cdr (assoc "val" org-link-abbrev-alist)) "org/Archive/" date-time)))
    (copy-directory org-directory org-backup-directory)
    (message "%s" (concat org-directory " copied to " org-backup-directory "!"))))
Electric Pair Tweak

see https://emacs.stackexchange.com/questions/2538/how-to-define-additional-mode-specific-pairs-for-electric-pair-mode

;; (defvar org-electric-pairs '((?/ . ?/) (?= . ?=)) "Electric pairs for org-mode.")
(defvar org-electric-pairs '((?/ . ?/) (?= . ?=) (?~ . ?~)) "Electric pairs for org-mode.")

  (defun org-add-electric-pairs ()
    (setq-local electric-pair-pairs (append electric-pair-pairs org-electric-pairs))
    (setq-local electric-pair-text-pairs electric-pair-pairs))

  (add-hook 'org-mode-hook 'org-add-electric-pairs)
(org-babel-tangle)
(load-file "~/.emacs.d/init.el")
org-capture-extension

https://github.com/sprig/org-capture-extension

ls -l "${HOME}/.local/share/applications/" | grep org
cat > "${HOME}/.local/share/applications/org-protocol.desktop" << EOF
[Desktop Entry]
Name=org-protocol
Exec=emacsclient %u
Type=Application
Terminal=false
Categories=System;
MimeType=x-scheme-handler/org-protocol;
EOF

update-desktop-database ~/.local/share/applications/

sudo update-desktop-database

org tree slide
(use-package org-tree-slide
  :custom
  (org-image-actual-width nil))
  • org-tree-slide-mode
  • Navivation: C-< org-tree-slide-move-previous-tree C-> org-tree-slide-move-next-tree
(with-eval-after-load "org-tree-slide"
  (define-key org-tree-slide-mode-map (kbd "<f9>") 'org-tree-slide-move-previous-tree)
  (define-key org-tree-slide-mode-map (kbd "<f10>") 'org-tree-slide-move-next-tree)
  )
org toc mode
(if (require 'toc-org nil t)
    (progn
      (add-hook 'org-mode-hook 'toc-org-mode)

      ;; enable in markdown, too
      (add-hook 'markdown-mode-hook 'toc-org-mode)
      (define-key markdown-mode-map (kbd "\C-c\C-o") 'toc-org-markdown-follow-thing-at-point))
  (warn "toc-org not found"))
google drive location menu
  (require 'setup-user-menu)
   (system-name)
   (string-match-p (regexp-quote "compute3") (system-name))
  (if (string-match-p (regexp-quote "compute3") (system-name))
      (print ";"))
(if (string-match-p (regexp-quote "compute3") (system-name)) (print ";"))
speedbar

the setup is broken, not using it at the moment

;; (require 'setup-speedbar)
Enable shellcheck

see https://github.com/federicotdn/flymake-shellcheck

An extended tutorial can be found here.

(use-package flymake-shellcheck
:commands flymake-shellcheck-load
:init
(add-hook 'sh-mode-hook 'flymake-shellcheck-load))
Shell promptRecommendations

https://stackoverflow.com/questions/12224909/is-there-a-way-to-get-my-emacs-to-recognize-my-bash-aliases-and-custom-functions/12229404#12229404

;; ->  make  all  envs  visible in  also org mode
(setq shell-file-name "bash")
(setq shell-command-switch "-ic")
  • The solution is to leave the shell-command-switch variable at its default value, which is just -c.

https://emacs.stackexchange.com/questions/3447/cannot-set-terminal-process-group-error-when-running-bash-script

(setq shell-file-name "bash")
(setq shell-command-switch "-c")
safe local variables
;; - '(safe-local-variable-values '((testvar\  . "hello")))
;; + '(safe-local-variable-values
;; +   '((pyvenv-activate . "~/.venvs/py37/")
;; +     (testvar\  . "hello")))
;;   '(sql-connection-alist
;;     '(("dataupload local container mysql"

;; (put 'pyvenv-activate 'safe-local-variable (lambda (_) t))

;; projectile-project-test-cmd :

(put 'pyvenv-activate 'safe-local-variable (lambda (_) t))
(put 'projectile-project-test-cmd 'safe-local-variable (lambda (_) t))
(put 'py-pythonpath  'safe-local-variable (lambda (_) t))

fix missing alt-key in WSL

WSL for Windows specific code

(setq x-alt-keysym 'meta)
(put 'set-goal-column 'disabled nil)
Collected Other Mode Configurations
;; (require 'setup-speedbar)

;; (eval-after-load 'sgml-mode '(require 'setup-html-mode))
(eval-after-load 'lisp-mode '(require 'setup-lisp))

(require 'setup-plantuml) ;; organizer todo notes etc

(require 'setup-latex)

(require 'setup-calendar)
;;(require 'setup-bash)
(require 'setup-octave)
;; (require 'mc)

;;(require 'setup-web-mode)
;; (require 'setup-jabber)
(require 'setup-chat-tracking)
;; (eval-after-load 'ruby-mode '(require 'setup-ruby-mode))
(eval-after-load 'clojure-mode '(require 'setup-clojure-mode))
;; (eval-after-load 'markdown-mode '(require 'setup-markdown-mode))
;;(require 'setup-pandoc)

;; Load slime-js when asked for
;; (autoload 'slime-js-jack-in-browser "setup-slime-js" nil t)
;; (autoload 'slime-js-jack-in-node "setup-slime-js" nil t)

;; Map files to modes
(require 'mode-mappings)


;; (require 'expand-region)
;; (require 'mark-more-like-this)
;; (require 'inline-string-rectangle)
;;(require 'multiple-cursors)
;; (require 'delsel)
;; (require 'jump-char)
;; (require 'eproject)
;; (require 'wgrep)
;; (require 'smart-forward)
;; (require 'change-inner)
;; (require 'multifiles)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Ansi Farben in compilation buffers:                                                                  ;;
;; Also hook:                                                                                           ;;
;; https://stackoverflow.com/questions/13397737/ansi-coloring-in-compilation-mode                       ;;
;; Als Function:                                                                                        ;;
;; https://stackoverflow.com/questions/23378271/how-do-i-display-ansi-color-codes-in-emacs-for-any-mode ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun display-ansi-colors ()
  (interactive)
  (let ((inhibit-read-only t))
    (ansi-color-apply-on-region (point-min) (point-max))))

(require 'ansi-color)
(defun colorize-compilation-buffer ()
  (toggle-read-only)
  (ansi-color-apply-on-region compilation-filter-start (point))
  (toggle-read-only))
(add-hook 'compilation-filter-hook 'colorize-compilation-buffer)
;; gehen alle nicht;
                                        ; (add-hook 'sbt-mode-hook 'display-ansi-colors)
;; (add-hook 'sbt-mode-hook 'ansi-color-for-comint-mode-on)
;; (add-to-list 'comint-output-filter-functions 'ansi-color-process-output)
;; (add-hook 'async-bytecomp-package-mode-hook 'colorize-compilation-buffer)

;; Fill column indicator
;; (require 'fill-column-indicator)

;; Browse kill ring
(require 'browse-kill-ring)
(setq browse-kill-ring-quit-action 'save-and-restore)

(require 'setup-ibuffer)
(require 'setup-doom-modeline)

;; (require 'setup-eclim)
;; This currently breaks dired icons. Why?
;; (require 'setup-scala)
(require 'setup-treemacs)
(require 'setup-groovy)
;; (require 'setup-eclim)

;; Misc
;; (require 'appearance)

;; (diminish 'eldoc-mode)
;; (diminish 'paredit-mode)

;; Elisp go-to-definition with M-. and back again with M-,
;; (autoload 'elisp-slime-nav-mode "elisp-slime-nav")
;; (add-hook 'emacs-lisp-mode-hook (lambda () (elisp-slime-nav-mode t) (eldoc-mode 1)))
;; (eval-after-load 'elisp-slime-nav '(diminish 'elisp-slime-nav-mode))

;; Email, baby
;; (require 'setup-mule)

;; Run at full power please
(put 'downcase-region 'disabled nil)
(put 'narrow-to-region 'disabled nil)

(put 'scroll-left 'disabled nil)


(setq abbrev-file-name             ;; tell emacs where to read abbrev
      "~/.emacs.d/abbrev_defs")    ;; definitions from...

;;(add-to-list 'load-path "/path/to/downloaded/openwith.el")
;;./elpa/openwith-20120531.1436/openwith.el:1

;; ("\\.pdf\\'"  "okular" (file))

(require 'openwith)
(setq openwith-associations '(
                              ("\\.pdf\\'"  "okular" (file))
                              ("\\.mp4\\'"  "vlc" (file))
                              ("\\.docx\\'" "lowriter" (file))
                              ("\\.odt\\'"  "lowriter" (file))
                              ("\\.pptx\\'"  "loimpress" (file))
                              ))
;; unset associations altogether
;; (setq openwith-associations '())

(openwith-mode)
(display-battery-mode)
(setq require-final-newline nil)

(require 'setup-nxml)
;; (require 'setup-pdf-tools)
(require 'setup-json-mode)
(require 'setup-magit)
;; (require 'setup-tags)

(require 'setup-flycheck-mode)
;; company mode autocompletion
;;(add-hook 'after-init-hook 'global-company-mode)

;;(require 'pasc-mode)

;; (require 'setup-supercollider)
(require 'setup-yaml-mode)
(require 'setup-editorconfig)
(require 'setup-rtags)
(require 'setup-treemacs)

(require 'setup-shell-scripting)
(require 'calfw)
(require 'calfw-gcal)
(require 'calfw-org)
(require 'calfw-gcal)
(require 'calfw-ical)

(put 'erase-buffer 'disabled nil)

;; fix misalignment in popus:
(setq popup-use-optimized-column-computation nil)

(add-hook 'makefile-mode-hook 'makefile-executor-mode)
yasnippet
(require 'setup-yasnippet)
(define-key yas-minor-mode-map [(tab)] nil)
(define-key yas-minor-mode-map (kbd "TAB") nil)
(message "nach yasnippet loading")
Auth Source, GPG, Security
;; not parseable by authinfo
(add-to-list 'auth-sources (joindirs org-directory "Notes.org.gpg"))
(find-file (joindirs org-directory "Notes.org.gpg"))
(defun delete-nth (index seq)
"Delete the INDEX th element of SEQ.
Return result sequence, SEQ __is__ modified."
(if (equal index 0)
(progn
(setcar seq (car (cdr seq)))
(setcdr seq (cdr (cdr seq))))
(setcdr (nthcdr (1- index) seq) (nthcdr (1+ index) seq))))
(delete-nth 0 auth-sources)

Add dropbox authinfo to auth source files

(add-to-list 'auth-sources (joindirs org-directory ".authinfo.gpg"))
(mapc 'message auth-sources)

(find-file (joindirs org-directory “.authinfo.gpg”)) (find-file (joindirs org-directory “Notes.org.gpg”)) ;; no need to add to auth sources as not parseable (auth-source-search :site “kaufland.de”) (auth-source-search :site “real.de”)

Print the list of auth sources.

(mapc 'message auth-sources)

https://www.arts-outdoors.de

(auth-source-search :host "real.de")

(auth-source-search :machine “mailprovider.com”) (find-file (joindirs org-directory “.authinfo.gpg”)) (auth-source-forget-all-cached) (find-file “~/.authinfo.gpg”) (mapc ‘message auth-sources) (auth-source-pass-get ‘secret “openai-key”)

Generate Key
gpg --full-generate-key
  • use rsa
  • size: 4096
  • never expires
  • Real Name
  • Email
  • PassPhrase
gpg --list-keys
# these should be in
ls -t ~/.gnupg/
ls -t ~/.gnupg/private-keys-v1.d -la

random_seed trustdb.gpg openpgp-revocs.d pubring.kbx private-keys-v1.d pubring.kbx~ total 8 -rw------- 1 christian christian 2056 Aug 21 13:00 3F10E5FB10073217E078BDB9F1043D5B7DD785EF.key -rw------- 1 christian christian 2056 Aug 21 13:00 676E806C8E7D02199000B22A4B86BFDBEAF035A6.key home/christian.gnupg/pubring.kbx


pub rsa4096 2021-08-21 [SC] B6791609BBC1CD7C000F17E75921C10409567BCA uid [ultimate] Christian Geng (my default key for storing encrypted passwords) <[email protected]> sub rsa4096 2021-08-21 [E]

trustdb.gpg openpgp-revocs.d pubring.kbx private-keys-v1.d pubring.kbx~

# Check if gpg-agent is already running
grep gpg-agent
# If it's not running, you can start it up with this command:
gpg-connect-agent /bye
Migrate key to other maschine

gpg –list-secret-keys [email protected]

gpg –export-secret-keys YOUR_ID_HERE > private.key gpg –import private.key

Lookup key

(defun efs/lookup-password (&rest keys) (let ((result (apply #’auth-source-search keys))) (if result (funcall (plist-get (car result) :secret)) nil)))

Migrate key to other machine

Identify your private key:

gpg –list-secret-keys [email protected]

pub   rsa4096 2021-08-21 [SC]
      <KEY ID DES SCHLÜSSELS>
uid           [ultimate] Christian Geng (my default key for storing encrypted passwords) <[email protected]>
sub   rsa4096 2021-08-21 [E]

Export key

gpg –export-secret-keys <KEY ID DES SCHLÜSSELS> > private.key

Copy Key to other machine (e.g. using scp)

import

gpg –import private.key

Enigmail / GnuPG v2 Note that you probably also have gpg2 on your system which is backwards-compatible with gpg, but seems to manage a separate list of keys. When using Thunderbird with Enigmail, note that it uses version 2 and may be unable to see your private key after importing. To fix that, run

COPY gpg2 –import private.key

More gpg interaction
GPG agent configuration
cat ~/.gnupg/gpg-agent.conf
Seems not to be effective (even after reload):

Information is from here.

gpgconf --kill gpg-agent
gpgconf --reload gpg-agent
# gpg-connect-agent reloadagent
gpgconf --list-options gpg-agent | grep default
gpgconf --list-options gpg-agent | grep max-cache
OS / Ubuntu specific?

Discussion about using gnone tools like seahorse or dconf-editor is found here.

I also had to use dconf-editor and used there recipe from here. And it worked indeed:

  • Lauch dconf-editor.
  • Navigate to desktop - gnome - crypto - cache.
  • change gpg-cache-method to idle or timeout.
  • change gpg-cache-ttl to the number of seconds you want the passphrase to be cached.
  • Restart the gnome-keyring daemon $ gnome-keyring-daemon -r
Mac Specific
;; Are we on a mac?
(setq is-mac (equal system-type 'darwin))
;; Setup environment variables from the user's shell.
(when is-mac (exec-path-from-shell-initialize))
;; (when is-mac (require 'mac))
codeium
Key Configuration

Found at this this post.

  (defun get-codeium-api-key ()
    "Retrieve the codeium API key from one of the authinfo files."
    (let ((auth (nth 0 (auth-source-search
                        :site "codeium.com"
                        :user "privat-email-account"
                        :max 1
                        :require '(:secret)))))
      (if auth
          (funcall (plist-get auth :secret))
        (error "No codeium API key found in authinfo file(s)"))))

(defvar codeium/metadata/api_key (get-codeium-api-key) "Your codeium key for accessing the ChatGPT API.")

(get-codeium-api-key) (codeium/metadata/api_key) (mapc ‘message auth-sources) ;; (setq codeium/metadata/api_key (get-codeium-api-key))

Installation
Manual installation - obsolete
(add-to-list 'load-path "~/.emacs.d/el/codeium/")
(load-file (joindirs straight-base-dir "straight" "build" "codeium" "codeium.el"))
;;  ~/.config/emacs/31.0.50/straight/build/codeium/codeium.el

(find-file straight-base-dir)

Straight for codeium
(straight-use-package '(codeium :type git :host github :repo "Exafunction/codeium.el"))
Codeium Configuration
;; we recommend using use-package to organize your init.el
(use-package codeium
    :straight t
    ;; if you use straight
    ;; :straight '(:type git :host github :repo "Exafunction/codeium.el")
    ;; otherwise, make sure that the codeium.el file is on load-path

    :init
    ;; use globally
    (add-to-list 'completion-at-point-functions #'codeium-completion-at-point)
    ;; or on a hook
    ;; (add-hook 'python-mode-hook
    ;;     (lambda ()
    ;;         (setq-local completion-at-point-functions '(codeium-completion-at-point))))

    ;; if you want multiple completion backends, use cape (https://github.com/minad/cape):
    ;; (add-hook 'python-mode-hook
    ;;     (lambda ()
    ;;         (setq-local completion-at-point-functions
    ;;             (list (cape-super-capf #'codeium-completion-at-point #'lsp-completion-at-point)))))
    ;; an async company-backend is coming soon!

    ;; codeium-completion-at-point is autoloaded, but you can
    ;; optionally set a timer, which might speed up things as the
    ;; codeium local language server takes ~0.2s to start up
    ;; (add-hook 'emacs-startup-hook
    ;;  (lambda () (run-with-timer 0.1 nil #'codeium-init)))

    ;; :defer t ;; lazy loading, if you want
    :config
    (setq use-dialog-box nil) ;; do not use popup boxes

    ;; if you don't want to use customize to save the api-key
    ;; (setq codeium/metadata/api_key "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")

    ;; get codeium status in the modeline
    (setq codeium-mode-line-enable
        (lambda (api) (not (memq api '(CancelRequest Heartbeat AcceptCompletion)))))
    (add-to-list 'mode-line-format '(:eval (car-safe codeium-mode-line)) t)
    ;; alternatively for a more extensive mode-line
    ;; (add-to-list 'mode-line-format '(-50 "" codeium-mode-line) t)

    ;; use M-x codeium-diagnose to see apis/fields that would be sent to the local language server
    (setq codeium-api-enabled
        (lambda (api)
            (memq api '(GetCompletions Heartbeat CancelRequest GetAuthToken RegisterUser auth-redirect AcceptCompletion))))
    ;; you can also set a config for a single buffer like this:
    ;; (add-hook 'python-mode-hook
    ;;     (lambda ()
    ;;         (setq-local codeium/editor_options/tab_size 4)))

    ;; You can overwrite all the codeium configs!
    ;; for example, we recommend limiting the string sent to codeium for better performance
    (defun my-codeium/document/text ()
        (buffer-substring-no-properties (max (- (point) 3000) (point-min)) (min (+ (point) 1000) (point-max))))
    ;; if you change the text, you should also change the cursor_offset
    ;; warning: this is measured by UTF-8 encoded bytes
    (defun my-codeium/document/cursor_offset ()
        (codeium-utf8-byte-length
            (buffer-substring-no-properties (max (- (point) 3000) (point-min)) (point))))
    (setq codeium/document/text 'my-codeium/document/text)
    (setq codeium/document/cursor_offset 'my-codeium/document/cursor_offset))
Codeium comany
(use-package company
    :defer 0.1
    :config
    (global-company-mode t)
    (setq-default
        company-idle-delay 0.05
        company-require-match nil
        company-minimum-prefix-length 0

        ;; get only preview
        company-frontends '(company-preview-frontend)
        ;; also get a drop down
        ;; company-frontends '(company-pseudo-tooltip-frontend company-preview-frontend)
        ))
Edit as sudo
(defun edit-current-file-as-root ()
  "Edit the file that is associated with the current buffer as root"
  (interactive)
  (if (buffer-file-name)
      (progn
        (setq file (concat "/sudo:localhost:" (buffer-file-name)))
        (find-file file))
    (message "Current buffer does not have an associated file.")))
Imenu auto
;; add Imenu whenever possible.
;; see https://www.emacswiki.org/emacs/ImenuMode for documentation
(defun try-to-add-imenu ()
  (condition-case nil (imenu-add-to-menubar "Index") (error nil)))
(add-hook 'font-lock-mode-hook 'try-to-add-imenu)
Visible Bell off
(setq visible-bell t)
;; ring-bell function not doing what its supposed to?
;; see https://www.emacswiki.org/emacs/AlarmBell
;; (defun ring-bell-function()
;;   "do not ring the bell when cursor has gone too far outside."
;;   (message "Went outside but not ringing the bell.")
;;     )
Ansible Vault Mode
(setq ansible-vault-password-file "~/.ansible/vault_pass.txt")
(add-to-list 'auto-mode-alist '("/encrypted$" . yaml-mode))

(defun ansible-vault-mode-maybe ()
  (when (ansible-vault--is-encrypted-vault-file)
    (ansible-vault-mode 1)))

(use-package ansible-vault
  :init (add-hook 'yaml-mode-hook 'ansible-vault-mode-maybe))
Themes

Modus Migration Guide to V4 should probably be reviewed: https://christiantietze.de/posts/2023/01/modus-themes-v4-changes/

;;; setup-themes.el --- summary -*- lexical-binding: t -*-

;; Author: CGeng
;; Maintainer: CGeng
;; Version: version
;; Package-Requires: (dependencies)
;; Homepage: homepage
;; Keywords: keywords


;;; Commentary:

;; commentary

;;; Code:

;;; name.el ends here
;; (load-theme 'fantom)
;; jetbrains-darcula
; doom-1337

;;(load-theme 'moe-light) - unfortunatel colors, got it from the supercollider guy
;; (load-theme 'doom-1337)

;;
;; Configure the Modus Themes' appearance
(setq modus-themes-mode-line '(accented borderless)
      modus-themes-bold-constructs t
      modus-themes-italic-constructs t
      modus-themes-fringes 'subtle
      modus-themes-tabs-accented t
      modus-themes-paren-match '(bold intense)
      modus-themes-prompts '(bold intense)
      ;; modus-themes-completions 'opinionated
      modus-themes-org-blocks 'tinted-background
      modus-themes-scale-headings t
      modus-themes-region '(bg-only)
      modus-themes-headings
      '((1 . (rainbow overline background 1.4))
        (2 . (rainbow background 1.3))
        (3 . (rainbow bold 1.2))
        (t . (semilight 1.1))))

;; Load the dark theme by default
(load-theme 'modus-vivendi t)


;; (load-theme 'wombat)
(defcustom cycle-themes '(material material-light doom-solarized-dark doom-solarized-light atom-dark intellij idea-darkula subatomic moe-light)
  "List of themes through which one can switch easily by calling
`cycle-themes' repeatedly. The first element is loaded at startup."
  :type '(repeat symbol))

(defvar cycle-current-theme nil
  "Used internally to hold a pointer to the currently loaded theme.")

(defun reload-current-theme ()
  "Reload the theme in `cycle-current-theme', if it is active."
  (interactive)
  (when (custom-theme-enabled-p cycle-current-theme)
    (load-theme cycle-current-theme t)))


;; andere gute thems:
;; deeper-blue
;; misterioso
;; tango-dark tango

(defun cycle-themes ()
  "Cycle through themes from the variable cycle-themes."
  (interactive)
  (let ((next-theme (car (or (cdr (memq cycle-current-theme cycle-themes))
                             cycle-themes))))
    (when next-theme
     (when (custom-theme-enabled-p cycle-current-theme)
       (disable-theme cycle-current-theme))
     (when (load-theme next-theme t)
       (setq cycle-current-theme next-theme)))))

;; (dolist (feature '(magit org-faces whitespace flyspell))
;;   (unless (featurep feature)
;;     (eval-after-load feature '(reload-current-theme))))


;; cycle theme once at startup.
;; (when (fboundp 'cycle-themes)
;;  (cycle-themes))

(provide 'setup-themes)
(require 'setup-themes)
csv mode
(require 'cl)
(require 'color)

(defun csv-highlight (&optional separator)
  (interactive (list (when current-prefix-arg (read-char "Separator: "))))
  (font-lock-mode 1)
  (let* ((separator (or separator ?\,))
         (n (count-matches (string separator) (point-at-bol) (point-at-eol)))
         (colors (cl-loop for i from 0 to 1.0 by (/ 2.0 n)
                       collect (apply #'color-rgb-to-hex
                                      (color-hsl-to-rgb i 0.3 0.5)))))
    (cl-loop for i from 2 to n by 2
          for c in colors
          for r = (format "^\\([^%c\n]+%c\\)\\{%d\\}" separator separator i)
          do (font-lock-add-keywords nil `((,r (1 '(face (:foreground ,c)))))))))
(add-hook 'csv-mode-hook 'csv-highlight)
(add-hook 'csv-mode-hook 'csv-align-mode)
(add-hook 'csv-mode-hook '(lambda () (interactive) (toggle-truncate-lines nil)))
Language-Tool

in the jars directory there is a download script https://github.com/mhayashi1120/Emacs-langtool?tab=readme-ov-file ;; (joindirs user-emacs-directory “jars” “LanguageTool-6.4” “languagetool-commandline.jar”)

(setq langtool-language-tool-server-jar (joindirs user-emacs-directory "jars" "LanguageTool-6.4" "languagetool-server.jar"))
(require 'langtool)
calibredb
(require 'calibredb)
(setq calibredb-root-dir "/D/Calibre_Science/")
(setq calibredb-db-dir (expand-file-name "metadata.db" calibredb-root-dir))

;;(setq calibredb-root-dir "~/OneDrive/Doc/Calibre")
;;(setq calibredb-db-dir (expand-file-name "metadata.db" calibredb-root-dir))
Ascidoctor

Link collection here:

https://www.emacswiki.org/emacs/AsciiDoc

Adoc Snippets

[email protected]:nicorikken/adoc-mode-yasnippet.git

see in snippets

open adoc files
(require 'adoc-mode)
(add-to-list 'auto-mode-alist '("\.adoc$" . adoc-mode))
;;  (add-to-list adoc-mode '("\\.adoc\\'" . adoc-mode))
(autoload 'adoc-mode "adoc-mode" nil t)
adoc mode preview
(defun rcd-command-output-from-input (program input &rest args)
  "Returns output from PROGRAM INPUT with optional ARGS"
  (let* ((output (with-temp-buffer
                   (insert input)
                   (apply #'call-process-region nil nil program t t nil args)
                   (buffer-string))))
    output))

(defun rcd-asciidoctor (string &rest args)
  (interactive)
  "Returns plain text from Markdown by using pandoc"
  (apply 'rcd-command-output-from-input "asciidoctor" string "-" args))

(defun rcd-asciidoctor-preview ()
  "Preview asciidoctor"
  (interactive)
  (let* ((output (rcd-asciidoctor (buffer-string)))
         (file (concat (or (getenv "TMPDIR") "/tmp/") "asciidoctor.html")))
    (with-temp-file file (insert output))
    (browse-url file)))

;; (global-set-key (kbd "C-c a") 'rcd-asciidoctor-preview)
Org ascidoc

Org ascidoc exporter Repo is here: git clone [email protected]:yashi/org-asciidoc.git

(add-to-list 'load-path "~/.emacs.d/el/org-asciidoc")
(require 'ox-asciidoc)
Always load .local_configs as shell script
(add-to-list 'auto-mode-alist '(".local_configs" . shell-script-mode))
Emacs Server
(require 'server)
(unless (server-running-p)
  (server-start))
Emacs as daemon

Startin the daemon

emacs --daemon
nohup_dated emacs --daemon &

Stopping the Emacs Daemon:

;; define function to shutdown emacs server instance
(defun server-shutdown ()
  "Save buffers, Quit, and Shutdown (kill) server"
  (interactive)
  (save-some-buffers)
  (kill-emacs)
  )

The link above also contains more fancy code that asks for unsaved buffers first.

Links:

https://medium.com/@lukaszkorecki/emacs-as-tmux-replacement-2acd10d7dfc8 https://emacs.stackexchange.com/questions/53036/switching-from-tmux-terminal-emacs-to-emacs-only https://emacs.stackexchange.com/questions/35587/emacs-client-cant-find-server-in-terminal

dired
(require 'setup-dired)
Get Temperature

Shell Script to get get temperatures

Web Server
(use-package simple-httpd
  :ensure t)
Supress always deleting trailing whitespace

None of these work yet.

  (add-hook 'write-file-hooks 'delete-trailing-whitespace nil t)
  (defun nuke_trailing ()
  (add-hook 'before-save-hook #'delete-trailing-whitespace nil t))
(add-hook 'prog-mode-hook #'nuke_trailing)

https://stackoverflow.com/questions/19174302/emacs-only-delete-trailing-whitespace-while-saving-in-programming-mode

Misc

Applications Config Example

Some App

This is an example of configuring another non-Emacs application using org-mode. Not only do we write out the configuration at .config/some-app/config, we also compute the value that gets stored in this configuration from the Emacs Lisp block above it.

(+ 55 100)

NOTE: Set the :tangle parameter below to .config/some-app/config for this to work!

;;  value=<<the-value()>>
(setq value <<the-value()>>)
;;  value=<<the-value()>>
(setq value <<the-value()>>)